Dynamic Variable References?

BlitzPlus Forums/BlitzPlus Programming/Dynamic Variable References?

eighsse(Posted 2014) [#1]
I'm used to using a language in which you can "dereference" a variable (I think I'm using that term correctly) by enclosing it in %'s, almost anywhere you want, allowing for things such as this:

currentPlayer = 2

player%currentPlayer%Speed = player%currentPlayer%Speed + 10

In this code, "player%currentPlayer%Speed" of course resolves to "player2Speed".

I'm having trouble finding any way that this can be done with Blitz Plus. Am I missing it, or is this not possible?


Floyd(Posted 2014) [#2]
That's typical of interpreted "scripting" languages.

In the style of your example, rather than manually building names like player1, player2, player3... you would use an array named player().


Yasha(Posted 2014) [#3]
In such scripting languages, a variable isn't really the same thing as it is in a compiled language: in BlitzPlus it becomes just a machine-code slot with no name (or need for a name) at runtime, whereas in highly dynamic scripting languages it's really a wrapper around a hidden map or hash table. Code that looks the same as an `x = x + 1` is actually doing something like `setValueForKey("x", getValueForKey("x") + 1)`. Which is why you can build up variables just like strings - because they actually are just strings in such languages.

Since BlitzPlus doesn't have such a hidden layer, if you really need to construct slot names at runtime, you'll need to use a data structure and build the indices explicitly. As Floyd points out the simplest case is to use a built-in array. If that's too simple for the names you need to construct (perhaps you aren't actually indexing with numbers?), you could try a TMap ( http://www.blitzbasic.com/codearcs/codearcs.php?code=2574 ), which gives decently fast access on any arbitrary string.

In practice you would probably do much better to re-architect your code to not need the dynamic elements at all, though. Even though your original example puts the number in the middle and adds a "speed" modifier, this is something you can do well with static code too, if you investigate custom types (and put objects of your custom "player" type, containing a "speed" property, into an array).


eighsse(Posted 2014) [#4]
Thank you both for your help; this makes sense. And Yasha I think you are right, restructuring things is probably the best way to do it. I'm just used to doing things a certain way because I've only used one language, and at first it feels like not being able to do things the same way will cause me to lose capabilities, but it's really probably just a matter of getting used to doing things a different way. Thanks again :D