0

I have a Lua function defined in a Java String, and I'd like to pass it a String arg

String luaCode = "function hello(name) return 'Hello ' + name +'!' end";

Executng code

public String runGreetingFromLua(String src, String arg) throws LuaException {
    L = LuaStateFactory.newLuaState();
    L.openLibs();
    L.setTop(0);
    int ok = L.LloadString(src);
    if (ok == 0) {
        L.getGlobal("debug");
        L.getField(-1, "traceback");
        L.remove(-2);
        L.insert(-2);
        L.getGlobal("hello");
        L.pushString(arg);
        ok = L.pcall(1, 0, -2);
        if (ok == 0) {
            String res = output.toString();
            output.setLength(0);
            return res;
        }
    }
    throw new LuaException(errorReason(ok) + ": " + L.toString(-1));
}

Getting Unknown error 5: error in error handling

I'm completely new to lua and luajava, I'm sure this simple case of not understanding how the LauState object is working, the java docs aren't amazing (or I'm missing something very newbie). I have been able to get a return value if I call the hello function from within the lua code and using print method. I'm executing on Android device using AndroLua

einverne
  • 6,454
  • 6
  • 45
  • 91
scottyab
  • 23,621
  • 16
  • 94
  • 105

1 Answers1

0

Managed to get this working by removing some of the error handling code as noted in the luajava examples that seemed to interfere and swapping call to L.LLloadString to L.LdoString(src); and L.pcall to L.call.

public String runLuaHello(String src, String arg) throws LuaException {
    //init 
    L = LuaStateFactory.newLuaState();
    L.openLibs();
    L.setTop(0);
    //load the lua source code
    int ok = L.LdoString(src);
    if (ok == 0) {
        //don't quite understand why it's getGlobal? but here you set the method name
        L.getGlobal("hello");
        //send the arg to lua
        L.pushString(arg);
        //this specifies 1 arg and 1 result
        L.call(1, 1);
        //get the result
        String result = L.toString(-1);
        //pop the result off the stack
        L.pop(1);
        return result;
    }
    throw new LuaException(errorReason(ok) + ": " + L.toString(-1));
}
scottyab
  • 23,621
  • 16
  • 94
  • 105