5

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

bislinux
  • 193
  • 2
  • 3
  • 12

1 Answers1

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
ryanpattison
  • 6,151
  • 1
  • 21
  • 28
  • 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. – verdy_p Sep 08 '21 at 16:48
  • 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). – verdy_p Sep 08 '21 at 17:35
  • 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```) – verdy_p Sep 10 '21 at 20:03