我已经很久没有使用Lua了,只用过C++。现在我正在努力重新理解一些更复杂的东西。
想象一下一个小型的实用函数,它的样子如下,可以为任意数量的参数多次调用一个函数:
-- helper to call a function multiple times at once
function smartCall(func, ...)
-- the variadic arguments
local args = {...}
-- the table to save the return values
local ret = {}
-- iterate over the arguments
for i,v in ipairs(args) do
-- if it is a table, we unpack the table
if type(v) == "table" then
ret[i] = func(unpack(v))
else
-- else we call the function directly
ret[i] = func(v)
end
end
-- return the individual return values
return unpack(ret)
end
那么我可以像这样做:
local a,b,c = smartCall(math.abs, -1, 2.0, -3.0)
local d,e,f = smartCall(math.min, {1.0, 0.3}, {-1.0, 2.3}, {0.5, 0.7})
这样做是可行的,但我想知道是否有更方便的方式,因为我的版本涉及大量的拆包和临时表。谢谢。
func
返回单个值;如果它返回多个值,则会被忽略。您确定这是您想要的吗? - kikito