如何使用带有参数的函数的xpcall?

Bla*_*ack 5 lua

这个网站上有一个例子,说明如何在没有参数的函数上使用xpcall.但是我如何在这样的函数上使用xpcall:

function add (a, b)
  return a + b
end
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

Eta*_*ner 6

如果您使用的是Lua 5.1,那么我相信您需要将所需的函数调用包装在另一个函数中(不带参数)并在调用中使用它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)
Run Code Online (Sandbox Code Playgroud)

在Lua 5.25.3中, xpcall现在直接接受函数参数:

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

此函数类似于pcall,但它设置了一个新的消息处理程序msgh.

所以电话会是:

status, err, ret = xpcall (f, err, 1, 2)
Run Code Online (Sandbox Code Playgroud)

在您的示例代码中.

  • 另请注意,LuaJIT尽管支持5.1,但也允许您通过xpcall传递参数. (2认同)