【问题标题】:Lua Insert table to tableLua 将表格插入表格
【发布时间】:2023-03-02 23:33:01
【问题描述】:

基本表,应该如何。但是我需要按功能来做,我该怎么做呢?

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

我怎样才能修复它们?

【问题讨论】:

  • config.return 无效,因为 return 是 lua 关键字。试试config["return"]。

标签: lua lua-table


【解决方案1】:

通过查看您的 createMenu 函数,可以发现两个明显的问题:

  1. 分配给 global tmp 每次 createMenu 是一个新表 调用。
  2. 使用return 关键字作为config 中的键。

如果您在 createMenu 函数之外的代码中的其他位置使用 tmp,则可能会出现问题。显而易见的解决方法是将其更改为:

local tmp = {}

对于第二个问题,如果你真的需要,可以使用 lua 关键字作为表键,但你不能使用 . 点语法来访问它,因为 Lua 会以错误的方式解析这个。相反,你需要改变:

config.return

到

config["return"].

编辑:阅读您的评论并检查示例表后,看起来只有按钮表是通过数字索引访问的。在这种情况下,您将只想在button 上使用table.insert。如果要创建具有关联键的表,则必须执行以下操作:

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 表。

【讨论】:

  • 是的,你说得对,但顶表 - 仅作为示例。所以 createMenu 函数应该创建表,使用 window = createMenu() 并通过函数发送窗口 - doCreateWindow(window, param1, callback)。 CreateMenu - 返回表。这里的问题 - 插入到 tmp 表 - 按钮表及其基于选项/外部数据的值(插入问题,因为 table.insert(tmp, {buttons[2] = {id = 4, value = "Text"} }) 对我不起作用)
  • @HappyDay 您必须更好地阐明您遇到的问题。调用createMenu 后的预期输出是什么?您希望返回的表格是什么样的?你实际上得到了什么?
  • 所以,只有 table.insert 有问题,我无法将值插入表格 - 表格内的按钮 tmp =(
  • table.insert 仅适用于表的索引部分。换句话说,在做table.insert之后,你的按钮表将在tmp[1]、tmp[2]等处。使用点语法或[]语法通过关联键插入。
  • 那么,我可以使用那个功能吗? table.insert(tmp.buttons, {id = 1, value = "text"}),它们会起作用吗?
猜你喜欢
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 2012-01-01
  • 2013-12-01
相关资源
最近更新 更多