示例
function func1()
return 1,1,1,1
end
table = {}
table = func1()
print(table)
我不想做
function func1()
return {1,1,1,1}
end
因为我使用的函数已经定义,我不能修改它。
期望的输出是
1 1 1 1
但事实并非如此;它只返回函数返回的第一个值。
我怎样才能做到这一点?抱歉格式错误;这是我第一次提问。
此外,我很确定该表等于一个数组?对此也感到抱歉。
编辑我也不知道参数的数量。
最佳答案
返回多个结果的函数将分别返回它们,而不是作为一个表。
Lua resource on multiple results: https://www.lua.org/pil/5.1.html
你可以像这样做你想做的事:
t = {func1()} -- wrapping the output of the function into a table
print(t[1], t[2], t[3], t[4])
此方法将始终获取所有输出值。
这个方法也可以使用table.pack
来完成:
t = table.pack(func1())
print(t[1], t[2], t[3], t[4])
通过使用 table.pack
,您可以丢弃 nil 结果。这有助于使用长度运算符 #
保留对结果数量的简单检查;然而,它是以不再保留结果“顺序”为代价的。
进一步解释,如果 func1
使用第一种方法返回 1, nil, 1, 1
,您会收到一个表,其中 t[2] ==无
。使用 table.pack
变体,您将得到 t[2] == 1
。
或者你可以这样做:
function func1()
return 1,1,1,1
end
t = {}
t[1], t[2], t[3], t[4] = func1() -- assigning each output of the function to a variable individually
print(t[1], t[2], t[3], t[4])
这种方法可以让你选择输出的位置,或者如果你想忽略一个你可以简单地做:
t[1], _, t[3], t[4] = func1() -- skip the second value
关于lua - 如何将多个值返回到表中?不返回表 [lua],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54916198/