我在 lua 中有一个函数,可以提供可变数量的输出。无论它有多少个输出,我怎样才能获得它的所有输出?
function my_function()
-- whatever
end
outputs_list = my_function()
上面的示例不起作用,因为
outputs_list
仅获取函数的第一个输出,所有其他输出都被丢弃。
我希望 outputs_list
包含该函数的所有输出,以便稍后检索它们。
我认为这在Python中相当于做
*outputs_list = my_function()
一般来说,您可以将值捕获到表
local t = { foo() }
但如果函数返回在列表中创建空洞的 nil 值,则它可能不是 序列。
select
可用于选择从哪里开始捕获返回值。
-- capture the second return value and onwards
local t = { select(2, foo()) }
table.pack(...)
,其中
返回一个新表,其中所有参数都存储在键 1、2 等中,并且字段“n”包含参数总数。请注意,如果某些参数为零,则结果表可能不是序列。
关于结果表不是序列的警告意味着循环所有返回值可能需要数字
for
而不是使用 ipairs
的通用值。
local function foo()
return 'a', 'b', 'c', 'd', 'e'
end
local results = table.pack(foo())
for i = 1, results.n do
print(results[i])
end
a
b
c
d
e
table.unpack
。
在 Lua 5.1 中,你可以将
table.pack
填充为
table.pack = function (...)
local t = { ... }
t.n = select('#', ...)
return t
end