lua

How to use xpcall with a function which has parameters?


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)

Solution

  • If you are using Lua 5.1, then 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, ret = xpcall (pcallfun, err)
    
    print (status)
    print (ret)
    

    In Lua 5.2, 5.3, and 5.4 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, ret = xpcall (f, err, 1, 2)
    

    in your sample code.

    As a comment points out, LuaJIT also accepts optional arguments after the error-handling function. (LuaJIT essentially targets Lua 5.1, but it extends stock Lua 5.1 in several ways.)