我有一个在Java字符串中定义的Lua函数,我想向它传递一个字符串arg
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的安卓设备上执行
发布于 2013-06-21 17:17:00
通过删除luajava示例中提到的一些错误处理代码,并将对L.LLloadString的调用交换到L.LdoString(src);,将L.pcall调用交换到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));
}https://stackoverflow.com/questions/17047003
复制相似问题