首页 > 解决方案 > 如何将多个值返回到表中?不返回表 [lua]

问题描述

例子

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

解决方案


返回多个结果的函数将分别返回它们,而不是作为表返回。

多个结果的 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使用第一种方法返回,您会收到一个表 where 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 

推荐阅读