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)
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 handlermsgh
.
So the call would be:
status, err, ret = xpcall (f, err, 1, 2)
in your sample code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With