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

时间:2022-01-25 11:00:12

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:

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

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):

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

2 个解决方案

#1


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.

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

In Lua 5.2 and 5.3 xpcall now accepts function arguments directly:

在Lua 5.2和5.3中,xpcall现在直接接受函数参数:

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

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

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

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

So the call would be:

所以电话会是:

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

in your sample code.

在您的示例代码中。

#2


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

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

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

#1


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.

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

In Lua 5.2 and 5.3 xpcall now accepts function arguments directly:

在Lua 5.2和5.3中,xpcall现在直接接受函数参数:

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

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

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

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

So the call would be:

所以电话会是:

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

in your sample code.

在您的示例代码中。

#2


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

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

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