Lua 插入表到表

标签 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
  }

表应该基于外部参数,并为每个选项变量编码一个表 - 不是更好的方法。我为此创建了一个函数,他们应该创建基本选项,如标题或描述并弹出,并将值插入按钮表(如果选项启用 - 添加按钮)。但这里的问题是,他们不会插入到 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/

    相关文章:

    c - 在 Lua 中,我应该如何处理来自 C 的从零开始的数组索引?

    class - 在Lua类中使用表变量

    lua - 从lua中另一个表内的表内调用函数

    javascript - 将 Lua 数据转换为 JSON

    lua - SHA2 512 的改编给出了不正确的结果

    lua - 确定变量是否是 Lua 中的几个值之一

    lua - 如何移动表格中的所有元素?

    lua - 如何在Lua中删除表?

    javascript - 用于网页设计的 Lua 控制台?

    lua cjson编码nil字段