表内有名称的表

Tables with names inside tables

所以我创建了一个 Lua 程序来跟踪我父亲购买的 属性 的需求,我想在带有名称的表中制作表。因此,当我尝试通过我创建的函数添加它时(我将展示该函数),它期望 ) 其中“=”是。

--The table I'm using to store everything
repair={}
--The function I'm using to create tables inside tables
function rAdd(name)
 table.insert(repair, name)
end
--The function I'm using to add data to those tables
function tAdd(table, name)
 table.insert(table, name)
end
rAdd(wall={})
tAdd(wall, "Due for paint job")

当我尝试添加它 (rAdd(wall={})) 时,它希望我在“=”处通过 ) 结束争论。请帮忙!

与其嘲弄 table.insert,不如使用 Lua tables 可以访问的事实,好吧 tables:

repair["wall"] = {}

现在您可以实际插入其中:

table.insert(repair["wall"], "Due for a paint job")

如果要将全局变量隐藏在函数后面:

function rAdd(name, value)
    repair[name] = value
end

rAdd("wall", {});

或者如果您真的想以 table 形式传递条目:

function rAddN(entries)
    for k,v in pairs(entries) do
        repair[k] = v
    end
end

rAddN({ wall = {} })

请注意,在这种情况下您可以省略括号:

rAddN { wall = {} }