lua - How to use xpcall with a function which has parameters? -


on this website there example on how use xpcall on function without parameters. how can use xpcall on function this:

function add (a, b)   return + b end 

and should return value. attempt (does not work, get: false, error in error handling, nil):

function f (a,b)   return + b end  function err (x)   print ("err called", x)   return "oh no!" end  status, err, ret = xpcall (f, 1,2, err)  print (status) print (err) print (ret) 

if using lua 5.1 believe need wrap desired function call in function (that takes no arguments) , use in call xpcall.

local function f (a,b)   return + b end  local function err (x)   print ("err called", x)   return "oh no!" end  local function pcallfun()     return f(1,2) end  status, err, ret = xpcall (pcallfun, err)  print (status) print (err) print (ret) 

in lua 5.2 , 5.3 xpcall accepts function arguments directly:

xpcall (f, msgh [, arg1, ···])

this function similar pcall, except sets new message handler msgh.

so call be:

status, err, ret = xpcall (f, err, 1, 2) 

in sample code.


Comments