4

我想打电话:

LuaState.pcall(num_args,num_returns, error_handler_index).  

我需要知道如何为这个函数设置错误处理程序。事实上,我认为如果有人展示了如何调用 Lua 函数并使用 LuaJava 返回数值结果,那就太好了。这可能会节省大量时间和问题。我正在寻找但没有找到错误函数的签名,以及如何将其放置在 LuaState 堆栈上的正确位置。所有 Java->Lua 示例要么打印一个没有返回的值,要么在使用 Lua 传入的 Java 对象上设置值。我想看看如何直接调用 Lua 函数并返回结果。

更新:一种解决方案是通过为错误处理程序传递零来使用 LuaState.pcall(1,1,0) 不传递错误处理程序:

String errorStr;
L.getGlobal("foo");
L.pushNumber(8.0);
int retCode=L.pcall(1,1,0);
if (retCode!=0){
    errorStr =  L.toString(-1);
}
double finalResult = L.toNumber(-1);

加载 calc.lua 的位置:

function foo(n) 
 return n*2 
end

现在有没有办法设置错误处理程序?谢谢

4

2 回答 2

1

如果您还想要堆栈回溯(我相信您会这样做:),您可以debug.traceback作为错误函数传递。看看它是如何在 AndroLua 中实现的

基本上,您必须确保您的堆栈设置如下:

  • 错误处理程序 ( debug.traceback)
  • 你要调用的函数
  • 参数

你可以用你的例子这样做:

L.getGlobal("debug");
L.getField(-1, "traceback");      // the handler
L.getGlobal("foo");               // the function
L.pushNumber(42);                 // the parameters
if (L.pcall(1, 1, -3) != 0) { ... // ... you know the drill...
于 2011-12-24T13:51:41.790 回答
0

假设您在某处有一个 Lua 函数来处理错误:

function err_handler(errstr)
  -- exception in progress, stack's unwinding but control 
  -- hasn't returned to caller yet
  -- do whatever you need in here
  return "I caught an error! " .. errstr
end

您可以将该函数传递err_handler到您的 pcall 中:

double finalResult;

L.getGlobal("err_handler"); 
L.getGlobal("foo");
L.pushNumber(8.0);

// err_handler, foo, 8.0
if (L.pcall(1, 1, -3) != 0)
{
    // err_handler, error message
    Log.LogError( L.toString(-1) );  // "I caught an error! " .. errstr
}
else 
{
    // err_handler, foo's result
    finalResult = L.toNumber(-1);
}
// After you're done, leave the stack the way you found it
L.pop(2);
于 2011-12-24T07:09:01.533 回答