Lua将表格插入表格

Hap*_*Day 5 lua lua-table

基本表,应该如何。但是我需要按功能进行操作,我该怎么做?

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
  }
Run Code Online (Sandbox Code Playgroud)

表应基于外部参数,并为每个选项变量编写一个表-更好的方法。我为此创建了一个函数,它们应该创建标题或描述之类的基本选项并弹出,然后将值插入按钮表(如果启用了选项-添加按钮)。但是这里的问题是,它们不会插入到tmp表,buttons表及其下一个选项的值中。

   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
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

gre*_*olf 5

createMenu功能上看,存在两个明显的问题:

  1. 每次都向全局 分配tmp一个新表createMenu
  2. 使用return关键字作为键config

如果您tmpcreateMenu函数外的代码中使用其他地方,则可能是一个问题。显而易见的解决方法是将其更改为:

local tmp = {}
Run Code Online (Sandbox Code Playgroud)

对于第二个问题,您可以根据需要使用lua关键字作为表键,但是.由于Lua会以错误的方式解析,因此您将无法使用点语法来访问它。相反,您需要更改:

config.return
Run Code Online (Sandbox Code Playgroud)

config["return"].
Run Code Online (Sandbox Code Playgroud)

编辑:在阅读您的注释并检查了示例表后,数字索引似乎只能访问按钮表。在这种情况下,你需要使用table.insertbutton。如果要创建具有关联键的表,则必须执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

这将生成mainMenu您在问题中描述的表格。