返回多个结果的函数将分别返回它们,而不是作为表格返回。
多个结果的 Lua 资源: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] == nil。使用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