LuaJava Setting an error handler for LuaState.pcall (a, b, error_function_index)?

I'm trying to call:

LuaState.pcall(num_args,num_returns, error_handler_index). 

I need to know how to install an error handler for this function. Actually, I think it would be nice for someone to show how to call the Lua function and get a numerical result using LuaJava. This can save a lot of time and questions. I am looking for but not finding a signature for the error function, and how to put it at the right point on the LuaState stack. All Java-> Lua examples either print a value without returning, or set values ​​for a Java object passed using Lua. I would like to see how to call the Lua function directly and return the result.

Update: one solution is to pass the error handler using LuaState.pcall (1,1,0), passing zero for the error handler:

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

where calc.lua is loaded:

 function foo(n) return n*2 end 

Now is there a way to install an error handler? Thanks

+4
source share
2 answers

If you also need a stack trace (I'm sure you did this :), you can pass debug.traceback as an error function. Take a look at how this is implemented in AndroLua .

Basically, you should make sure your stack is configured as follows:

  • Error Handler ( debug.traceback )
  • The function you want to call
  • Options

You can do this in the following example:

 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... 
+1
source

Assuming you have a Lua function to handle the error:

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

You can pass this err_handler function to your 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 result finalResult = L.toNumber(-1); } // After you're done, leave the stack the way you found it L.pop(2); 
0
source

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


All Articles