6

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

1
  • Define add(...) as foldl1(function(x,y) return x+y end, {...}) Commented Aug 18, 2015 at 11:39

1 Answer 1

9
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
Sign up to request clarification or add additional context in comments.

3 Comments

Note that there's a limit on the number of arguments for function calls accepted by the Lua parser. For example: 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.
The actual limit also depends on which Lua version or engine you use (and there may be lower limits set by the environment, Lua seems to just want the support of at least 50 arguments in function calls. That limit may change in Lua depending on the bytecode implementation for the interpreter, but a Lua engine may not need to use that bytecode and JIT-compile it to native code which does not have this limit but may have another one on the system call stack (if this is where upvalues are allocated) or in user quota (or per-process quota or per-thread quotas on dynamically allocatable memory).
Also note that the recursive call to 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.