基本表,它们应该如何。但是我需要按功能来做,我该怎么做?
local mainMenu = {
caption = "Main Window",
description = "test window",
buttons = {
{ id = 1, value = "Info" },
{ id = 2, value = "Return" },
{ id = 3, value = "Ok" },
{ id = 4, value = "Cancel" }
},
popup = true
}
表应该基于外部参数,并为每个选项变量编码一个表 - 不是更好的方法。我为此创建了一个函数,他们应该创建基本选项,如标题或描述并弹出,并将值插入按钮表(如果选项启用 - 添加按钮)。但这里的问题是,他们不会插入到 tmp 表、按钮表及其下一个选项的值。
function createMenu()
tmp = {}
--buttons insert
if(config.info) then
table.insert(tmp, {buttons = {id = 1, value = "Info"}});
elseif(config.return) then
table.insert(tmp, {buttons = {id = 2, value = "Return"}});
end
--table main
table.insert(tmp, {
caption = "Main Window",
description = "test window",
popup = true
})
return tmp
end
我如何修复它们?
最佳答案
从看着你的 createMenu
功能,两个明显的问题突出:
tmp
每次换一张新表 createMenu
是叫。
return
关键字作为 config
中的键. 如果您使用
tmp
,可能会出现问题createMenu
之外的代码中的其他位置功能。显而易见的解决方法是将其更改为:local tmp = {}
对于第二个问题,如果你真的想要,你可以使用 lua 关键字作为表键,但你将无法使用
.
点语法来访问它,因为 Lua 会以错误的方式解析它。相反,您需要更改:config.return
到
config["return"].
编辑 :阅读您的评论并检查示例表后,看起来只有按钮表是通过数字索引访问的。在这种情况下,您需要使用
table.insert
仅在 button
.如果要创建具有关联键的表,则必须执行以下操作:function createMenu()
local tmp =
{
--table main
caption = "Main Window",
description = "test window",
popup = true,
--button table
buttons = {}
}
--buttons insert
if config.info then
table.insert(tmp.buttons, {id = 1, value = "Info"});
elseif config['return'] then
table.insert(tmp.buttons, {id = 2, value = "Return"});
end
return tmp
end
这将产生
mainMenu
您在问题中描述的表格。
关于Lua 插入表到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17387031/