1

How does one get the value back from a Lua function call in LuaJava.

Lets say I have calc.lua:

function foo(n) return n*2 end

I call the function in Java as follows:

LuaState luaState;
this.luaState = LuaStateFactory.newLuaState();
this.luaState.openLibs();
this.luaState.LdoFile("calc.lua");
this.luaState.getGlobal("foo");
this.luaState.pushNumber(5.0);
int retcode=this.luaState.pcall(1, 1,0);

Now what do I have to call on LuaState object to get the result of this last function call foo(5)?

Is there an example somewhere showing Java->Lua invocation with return values from the call?

Androider
  • 21,125
  • 36
  • 99
  • 158

1 Answers1

2

Would something like this do the trick?

int top_index = luaState.getTop();
double result = luaState.isNumber(top_index) ? 
                luaState.toNumber(top_index) : 0.0;
greatwolf
  • 20,287
  • 13
  • 71
  • 105
  • 2
    Lua also allows you to use negative index to point from the top of the stack. So essentially you only need to do `double result = luaState.toNumber(-1)`, because it will return 0 if it is not a number. – Michal Kottman Dec 23 '11 at 09:37
  • Thanks. I'm still having issues executing the LuaState.pcall(..) Basically I'm not getting return value do to some error during execution of pcall(..) http://stackoverflow.com/questions/8621471/luajava-error-in-error-handling – Androider Dec 23 '11 at 23:20