Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a dynamic variable name in Lua?

Tags:

lua

I am new to Lua and am having some difficulties:

I am trying to create dynamic variable names:

local tblAlphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

local count = 0;

for k, v in pairs (tblAlphabet) do

  count = count + 1;

  [v.."button"]  = ui.newButton{ --HOW DO I MAKE THIS WORK? I get syntax error

--some code here

  }
like image 703
jini Avatar asked Feb 21 '11 02:02

jini


3 Answers

You can create a table which contains your variables.

local tblAlphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}
local vars = {}
for k, v in pairs(tblAlphabet) do
    vars[v .. "_button"] = ui.newButton()
end

Then you can access vars via iterators or direct access (vars.a_button).

like image 177
ponzao Avatar answered Sep 23 '22 15:09

ponzao


it's not clear what you want to do; but if you want to programmatically create lots of global variables, just remember that globals are fields of the _G table:

_G['anyvar'] = 'something'
print (anyvar)
like image 42
Javier Avatar answered Sep 26 '22 15:09

Javier


The variables you create are first-class values that do not have names.

You can assign them to variables which have names. Either local variables, or in this case (since you want to do it in a loop), key names in a table (either the globals table, or a table you create).

You do not need a data table to create your button names, since they follow a simple pattern.

t = {}
for b = string.byte('a'), string.byte('z') do
    c = string.char(b)              -- 'a' to 'z'
    t['button'..c] = ui.newButton() -- something like this
end
like image 43
mlepage Avatar answered Sep 24 '22 15:09

mlepage