Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable name to include value of another variable

Tags:

variables

lua

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?

like image 875
Tomha Avatar asked Nov 06 '13 08:11

Tomha


2 Answers

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].

like image 109
Lorenzo Donati -- Codidact.com Avatar answered Sep 23 '22 12:09

Lorenzo Donati -- Codidact.com


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
like image 43
Yu Hao Avatar answered Sep 22 '22 12:09

Yu Hao