Dynamic variable reference?

Is it possible to store a variable name inside a different variable for later dynamic reference?

In my example, I have a set of towns that can be linked by trade routes. In one town’s interface (Sulphur Springs), the player would indicate the target town (Underwood), and the code will set each town’s trade target as the other, e.g.:

(set: $SulphurSpringsTradeTarget to "Underwood")
(set: $UnderwoodTradeTarget to "Sulphur Springs")

The problem comes when I want to cancel a trade route. I would like to be able to cancel the route in one town’s interface (e.g. cancel in the Underwood menu) and have it reset the value of both “SulphurSpringsTradeTarget” and “UnderwoodTradeTarget”. However, I can’t figure out a way to make this work since the second town could be any of a variety of town names, so it can’t be a static variable reference.

I tried setting up a TradeLinks datamap which, when a route is established, would store both sides of the trade route:

(set: $TradeLinks to it + (dm: "SulphurSpringsTradeTarget", "UnderwoodTradeTarget"))
(set: $TradeLinks to it + (dm: "UnderwoodTradeTarget", "SulphurSpringsTradeTarget"))

My hope was that I’d be able to then populate the cancel command with the destination from the datamap:

(set: $UnderwoodTradeTarget to " ")
(set: "$" + $TradeLinks's UnderwoodTradeTarget to " ")

But Harlowe doesn’t like me having anything other than a straight variable name to the left of the “to” in the set: command.

Any suggestions on how to achieve this goal would be very much appreciated!

1 Like

What you’d like to accomplish is something akin to JavaScript’s eval() function where you can pass in a string and have it evaluated as run-time code. I don’t believe this exists in Harlowe, though I’m a bit rusty on Harlowe currently.

I did find this answer from back in 2017 with a very similar question. The solution was to use an array, but I think a datamap will work for what you want to accomplish. Think of a datamap as a parent variable of dynamic child variable names and values. You should be able to assemble a dynamic child name and retrieve the value that way.

I hope that makes sense. I haven’t tested this, but I’m familiar with the concept and it should work with Harlowe in this manner. Let us know if this helps. :slight_smile:

I hope I’m not sending you on a wild goose chase. :wink:

This put me on the right track – thank you! I had to rebuild the way I was doing some of my variables but I think I’ve got it working the way I want now. Appreciate the help!

1 Like