如何让Lua函数返回键值对到一个尚未填充的表格中?

我希望键值对为tableToPopulate.width = 30和tableToPopulate.Height = 20 它们当前为tableToPopulate [1] = 30和tableToPopulate [2] = 20


本地函数X()
     代码,代码......
     返回30,20
end

local tableToPopulate = {
    x()
}
点赞
用户1973793
用户1973793

为什么不直接返回一个表格呢?

local function X ()
    return {width=30, height=20}
end
2013-04-12 18:53:25
用户1208078
用户1208078

你可以传入你想要设置值的表格,就像这样:

function x(tbl)
    tbl.Height = 20;
    tbl.Width = 30;
end

local t={}
x(t)
print(t.Height, t.Width)

但是,根据表格中包含的内容的结构有多复杂,使用嵌套表格可能更有意义。

function x(tbl)
    table.insert(tbl, {Height = 20, Width = 30})
end

local t={}
x(t)
print(t[1].Height, t[1].Width)

这相当于:

function x()
    return {Height = 20, Width = 30}
end
local t = {x()}
print(t[1].Height, t[1].Width)

所以,它真的取决于你想如何组织数据以及哪种语法更符合你的喜好。

2013-04-12 20:32:47