如何在具有参数的函数中使用xpcall?

这个网站 上有一个关于如何在没有参数的函数上使用 xpcall 的示例。但是我如何在像这样一个函数上使用 xpcall:

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

它应该获得返回值。 这是我的尝试(不起作用,我会得到: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)
点赞
用户258523
用户258523

如果您使用的是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)

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

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

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

因此,在您的示例代码中,调用将为:

status, err, ret = xpcall (f, err, 1, 2)
2015-05-08 14:05:49
用户4684797
用户4684797
```lua
function f (a,b)
  return a + b
end

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

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

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

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

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

将Lua函数 f(a,b) 定义为返回 a+b,接下来使用 xpcall 来调用函数 f,使用 debug.traceback 处理任何错误。最后打印出 statusreterr 变量的值。

2016-08-23 13:46:23