LuaJava Error in Error Handling

我只是一个虾纸丫 提交于 2019-12-02 04:15:43

问题


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

function foo(n) return n*2 end

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"

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

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


回答1:


This is taken from the Lua reference manual -- under the C API section it says this about 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);

...

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

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



回答2:


Why on earth have you provided -2? That should not be there. You have told Lua that on the Lua stack there exists an error function that will deal with the error at the index -2, while your code does not indicate anything of the sort. pcall should only take two arguments in most cases.



来源:https://stackoverflow.com/questions/8621471/luajava-error-in-error-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!