LuaJava error handling errors

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

function foo(n) return n*2 end 

That's all there is in calc.lua and subsequent command line calls.

Here is a call that always has an 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 also tried L.remove (-2); L.insert (-2);

Not sure why he gives any kind of error at all or what the error is. Maybe I'm setting up an error handler incorrectly? So this is not a challenge? After loading, I tried from the console and was able to run print (foo (5)), returning 10 as expected.

UPDATE: Looks like I need to provide an error handler on the stack. What is the signature for such an error handler and how can I put it on a point on the stack. Thanks

+2
source share
2 answers

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

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

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

...

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

So, assuming the LuaJava API just reflects 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) : ""; 
+1
source

Why did you provide -2? It should not be. You told Lua that there is an error function in the Lua stack that will handle the error at index -2, while your code does not indicate anything like that. pcall should accept only two arguments in most cases.

0
source

Source: https://habr.com/ru/post/1387504/


All Articles