如何将多个值返回到表中?不返回表 [lua]

The*_*iro 3 lua

例子

function func1()
 return 1,1,1,1
end

table = {}
table = func1()

print(table)
Run Code Online (Sandbox Code Playgroud)

我不想做

 function func1()
  return {1,1,1,1}
 end
Run Code Online (Sandbox Code Playgroud)

因为我使用的函数已经定义,我无法修改它。

所需的输出是

1 1 1 1

但这种情况并非如此; 它只返回函数返回的第一个值。

我怎样才能使这成为可能?抱歉,格式错误;这是我第一次提问。

另外,我很确定该表等于一个数组?对此也很抱歉。

编辑我也不知道参数的数量。

Nif*_*fim 8

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

多个结果的 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])
Run Code Online (Sandbox Code Playgroud)

此方法将始终获得所有输出值。


此方法也可以使用以下方法完成table.pack

t = table.pack(func1())
print(t[1], t[2], t[3], t[4])
Run Code Online (Sandbox Code Playgroud)

通过使用table.pack你可以丢弃零结果。这有助于使用长度运算符保留对结果数量的简单检查#;然而,这是以不再保留结果“顺序”为代价的。

为了进一步解释,如果使用第一种方法func1返回,您会收到一个表,其中. 随着变化你会得到。1, nil, 1, 1t[2] == niltable.packt[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])
Run Code Online (Sandbox Code Playgroud)

此方法可以让您选择输出的去向,或者如果您想忽略一个,您可以简单地执行以下操作:

 t[1], _, t[3], t[4] = func1() -- skip the second value 
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用 `t = table.pack(func1())` 而不是 `t = {func1()}` 因为这样您就可以使用 `tn` 查询表中的元素数量(`#t` 不起作用如果有“洞”)。 (4认同)