首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在AndroLua中使用LuaJava将字符串arg传递给Lua方法

在AndroLua中使用LuaJava将字符串arg传递给Lua方法
EN

Stack Overflow用户
提问于 2013-06-11 22:45:02
回答 1查看 465关注 0票数 0

我有一个在Java字符串中定义的Lua函数,我想向它传递一个字符串arg

代码语言:javascript
复制
String luaCode = "function hello(name) return 'Hello ' + name +'!' end";

执行代码

代码语言:javascript
复制
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的安卓设备上执行

EN

回答 1

Stack Overflow用户

发布于 2013-06-21 17:17:00

通过删除luajava示例中提到的一些错误处理代码,并将对L.LLloadString的调用交换到L.LdoString(src);,将L.pcall调用交换到L.call,成功地实现了这一点。

代码语言:javascript
复制
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));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17047003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档