Lets say I have pre-defined 3 variables, x1
, x2
, and x3
, each of which is a different co-ordinate on the screen. I have a whole chunk of code to decide whether another variable, a
will equal 1
, 2
, or 3
. Now, I want to include the value of a in a variable name, allowing me to 'dynamically' change between x1
, x2
, and x3
.
E.g. a
is set to 2
. Now I want to move the mouse to xa
, so if a=2
, xa
is x2
, which is a predefined variable.
Its probably clear I am very new to Lua, I have tried googling the issue, but I'm not really sure what I am looking for, terminology wise and such.
Anyhow, is anyone able to help me out?
If you can change the code where x1
, x2
and x3
are defined, a cleaner approach is to use arrays (i.e. array-like tables). This is the general approach when you need a sequence of variables indexed by a number.
Therefore, instead of x1
, x2
and x3
you could define:
local x = {}
x[1] = 10 -- instead of x1
x[2] = 20 -- instead of x2
x[3] = 30 -- instead of x3
Now instead of using xa
you simply use x[a]
.
If xa
are global variables, you can use the table _G
like this:
x1 = 42
x2 = 43
x3 = 44
local a = 2
print(_G['x' .. a])
Output:
43
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With