I am looking for a way to pcall a function which has variable arguments in lua5.3.
I am hoping for something like this
function add(...)
local sum=arg + ...
return sum
end
stat,err=pcall(add,...)
thanks
function add(...)
local sum = 0
for _, v in ipairs{...} do
sum = sum + v
end
return sum
end
pcall(add, 1, 2, 3)
--> true 6
or maybe this is closer to what you wanted:
function add(acc, ...)
if not ... then
return acc
else
return add(acc + ..., select(2, ...))
end
end
pcall(add, 1, 2, 3)
--> true 6
add(0,1,2,3,--[[enumerate other integers here]],241,242) may work, while add(0,1,2,3,--[[enumerate other integers here]],241,242,243) will send error an error: function or expression too complex near ')'. This limit is related to a limit on the number of accessible upvalues in the Lua VM bytecode, and a reserve kept for system calls at runtime.add() in the solution is a trailing call, so Lua compiles it as a loop: it iterates after reducing 2 arguments acc and ...[1] by the addition acc+..., and shifting all other arguments in ... to the left, using select(2, ...). The loop iterates at most 242 times (because of the limit on the number of arguments in function calls), or less (some Lua versions or environments allow no more than 50 arguments, including the implicit 1st argument self for functions name with a colon prefix, e.g.object:name)
add(...)asfoldl1(function(x,y) return x+y end, {...})