【问题标题】:Passing String arg to Lua method with LuaJava in AndroLua在 AndroLua 中使用 LuaJava 将字符串 arg 传递给 Lua 方法
【发布时间】:2013-06-07 11:22:03
【问题描述】:

我在 Java 字符串中定义了一个 Lua 函数,我想传递一个字符串参数

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

执行代码

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));
}

获取Unknown error 5: error in error handling

我对 lua 和 luajava 完全陌生,我确信这个简单的案例是不了解 LauState 对象是如何工作的,java 文档并不令人惊奇(或者我错过了一些非常新手的东西)。如果我从 lua 代码中调用 hello 函数并使用 print 方法,我已经能够获得返回值。我正在使用 AndroLua 在 Android 设备上执行

【问题讨论】:

    标签: android luajava androlua


    【解决方案1】:

    通过删除 luajava 示例中指出的一些似乎干扰的错误处理代码并将对L.LLloadString 的调用交换为L.LdoString(src);L.pcallL.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));
    }
    

    【讨论】:

    • 恐怕没有,tbh 已经好几年没在 Android 上看过 lua 了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多