lua - 如何将多个值返回到表中?不返回表 [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 资源: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
推荐阅读
- java - 我试图更新 BlockBreakEvent 上的项目,但它没有正确更新
- flutter - Flutter 如何在 assets_audio_player 中获取当前持续时间
- java - 如何提供一些从 maven 到 Google Compile-Testing 的库
- css - 动态导入样式和设置scss变量值
- reactjs - 在使用 React Hooks 时,我们如何在一开始为一些复杂的数据结构设置状态?
- image - 带有渐变边框颜色的颤振图像
- c# - ASP.Net 网络表单
- javascript - 什么时候应该在 NavLink 上使用 Link?
- git - 将特定文件同步到 repo
- javascript - 如何使用 fetch 将更新的变量从客户端发送到服务器?