Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pcall with variable argument in lua

Tags:

lua

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

like image 553
bislinux Avatar asked Aug 18 '15 11:08

bislinux


1 Answers

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
like image 90
ryanpattison Avatar answered Sep 29 '22 21:09

ryanpattison