Reputation: 21335
I am trying to call:
LuaState.pcall(num_args,num_returns, error_handler_index).
I need to know how to set the error handler for this function. In fact, I think it would be nice it someone showed how to invoke a Lua function and get a numerical result back using LuaJava. This might save a lot of time and questions. I am looking but not finding the signature for the error function, and how to place it at the right point on the LuaState stack. All the Java->Lua examples are either printing a value with no return or they are setting values on a Java object passed in using Lua. I would like to see how to call a Lua function directly and get the result back.
Update: one solution is to pass no error handler using LuaState.pcall(1,1,0) by 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 has been loaded:
function foo(n)
return n*2
end
Now is there a way to set an error handler as well? Thanks
Upvotes: 4
Views: 832
Reputation: 16753
If you also want the stack traceback (I'm sure you do :), you can pass debug.traceback
as the error function. Take a peek at how it's implemented in AndroLua.
Basically, you have to make sure your stack is set up as follows:
debug.traceback
)You can do it like this with your 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...
Upvotes: 1
Reputation: 20838
Assuming you have a Lua function somewhere to handle the error:
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
You can pass that err_handler
function into 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's result
finalResult = L.toNumber(-1);
}
// After you're done, leave the stack the way you found it
L.pop(2);
Upvotes: 0