Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use xpcall with a function which has parameters?

Tags:

lua

On this website there is an example on how to use xpcall on a function without parameters. But how can i use xpcall on a function like this:

function add (a, b)
  return a + b
end

And it should get the return value. This is my attempt (does not work, i get: false, error in error handling, nil):

function f (a,b)
  return a + 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)
like image 314
Black Avatar asked May 08 '15 13:05

Black


1 Answers

If you are using Lua 5.1 then I believe you need to wrap your desired function call in another function (that takes no arguments) and use that in the call to xpcall.

local function f (a,b)
  return a + 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 and 5.3 xpcall now accepts function arguments directly:

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

This function is similar to pcall, except that it sets a new message handler msgh.

So the call would be:

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

in your sample code.

like image 71
Etan Reisner Avatar answered Oct 09 '22 22:10

Etan Reisner