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

4

1 回答 1

0

通过删除 luajava 示例中指出的一些错误处理代码,这些代码似乎会干扰并交换对L.LLloadStringtoL.LdoString(src);L.pcallto 的调用,从而设法使其正常工作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));
}
于 2013-06-21T09:16:59.707 回答