如何将 xpcall 与具有参数的函数一起使用?

How to use xpcall with a function which has parameters?

this website 上有一个关于如何在不带参数的函数上使用 xpcall 的示例。但是我如何在这样的函数上使用 xpcall:

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

它应该得到 return 值。 这是我的尝试(不起作用,我得到:错误,错误处理错误, 无):

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)

如果您使用的是 Lua 5.1,那么我相信您需要将所需的函数调用包装在另一个函数(不带参数)中,并在对 xpcall.[= 的调用中使用它19=]

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 现在直接接受函数参数:

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

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

所以电话会是:

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

在您的示例代码中。

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

status, ret, err = xpcall (f, debug.traceback, 1,5)

print (status)
print (ret)
print (err)