错误处理中的 LuaJava 错误 [英] LuaJava Error in Error Handling

查看:15
本文介绍了错误处理中的 LuaJava 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 LuaJava 从 Java 调用一个简单的 Lua 函数.calc.lua:

I am trying to call a simple Lua function from Java using LuaJava. calc.lua:

function foo(n) return n*2 end

这就是 calc.lua 和来自命令行工作的后续调用的全部内容.

Thats all there is in calc.lua and subsequent calls from command line work.

这是总是有错误的调用:

Here is the call that always has error :

L.getGlobal("foo");     
L.pushNumber(8.0);
int retCode=L.pcall(1, 1,-2); // retCode value is always 5 pcall(numArgs,numRet,errHandler)
String s = L.toString(-1);     // s= "Error in Error Handling Code"

我也试过
L.remove(-2);L.insert(-2);

I have also tried
L.remove(-2); L.insert(-2);

不知道为什么它会给出任何错误或错误是什么.也许我没有正确设置错误处理程序?所以它不打电话?加载后,我从控制台尝试并可以运行 print(foo(5)) 按预期返回 10.

Not sure why its giving any error at all or what the error is. Maybe I'm not setting up error handler correctly? So it does not make the call? After load I tried from console and can run print(foo(5)) getting back 10 as expected.

更新:看起来我需要在堆栈上提供一个错误处理程序.这种错误处理程序的签名是什么,我将如何将其放置在堆栈上的某个点.谢谢

UPDATE: It looks like I need to provide an error handler on the stack. What is the signature for such an error handler and how would I place it at a point on the stack. Thanks

推荐答案

这取自 Lua 参考手册——在 C API 部分 它是关于 pcall 的:

This is taken from the Lua reference manual -- under the C API section it says this about pcall:

当您使用 lua_call 调用函数时,被调用函数内的任何错误都会向上传播(使用 longjmp).如果你需要处理错误,那么你应该使用 lua_pcall:

When you call a function with lua_call, any error inside the called function is propagated upwards (with a longjmp). If you need to handle errors, then you should use lua_pcall:

  int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);

...

如果 errfunc 为 0,则返回的错误信息正是原始错误消息.否则,errfunc 给出堆栈索引一个错误处理函数.(在当前的实现中,该索引不能是伪索引.)在运行时错误的情况下,该函数将使用错误消息调用,其返回值将是lua_pcall 返回的消息

If errfunc is 0, then the error message returned is exactly the original error message. Otherwise, errfunc gives the stack index for an error handler function. (In the current implementation, that index cannot be a pseudo-index.) In case of runtime errors, that function will be called with the error message and its return value will be the message returned by lua_pcall

所以假设 LuaJava 的 API 只是镜像 C API,那么只需传递 0 表示没有特殊的 errfunc.这样的事情应该可以工作:

So assuming LuaJava's API just mirrors the C API, then just pass 0 to indicate no special errfunc. Something like this should work:

int retCode = L.pcall(1, 1, 0);
String errstr = retCode ? L.toString(-1) : "";

这篇关于错误处理中的 LuaJava 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆