我是Lua的新手并且遇到了一些困难:
我正在尝试创建动态变量名称:
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
}
答案 0 :(得分:13)
您可以创建一个包含变量的表。
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
然后您可以通过迭代器或直接访问(vars
)访问vars.a_button
。
答案 1 :(得分:7)
目前尚不清楚你想做什么;但是如果你想以编程方式创建许多全局变量,请记住全局变量是_G
表的字段:
_G['anyvar'] = 'something'
print (anyvar)
答案 2 :(得分:1)
您创建的变量是没有名称的第一类值。
您可以将它们分配给具有名称的变量。局部变量,或者在这种情况下(因为你想在循环中完成),表中的键名(全局表或你创建的表)。
您不需要数据表来创建按钮名称,因为它们遵循简单的模式。
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