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
}
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
).
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)
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
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