문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top