我正在尝试使用LuaJ在Java程序中调用lua函数.当我没有向闭包传递任何参数时,它工作正常:
String script = "print 'Hello World!'";
InputStream input = new ByteArrayInputStream(script.getBytes());
Prototype prototype = LuaC.compile(input, "script");
LuaValue globals = JsePlatform.standardGlobals();
LuaClosure closure = new LuaClosure(prototype, globals);
closure.call();
Run Code Online (Sandbox Code Playgroud)
但是现在我正在尝试一个带有顶级函数的lua脚本,该函数接受一个参数而我无法弄清楚如何从Java中传入参数.这是我到目前为止所得到的:
String script = "function something(argument)\n"+
"test_string = 'Hello World!'\n"+
"print(test_string)\n"+
"print(argument)\n"+
"end";
InputStream input = new ByteArrayInputStream(script.getBytes());
Prototype prototype = LuaC.compile(input, "script");
LuaValue globals = JsePlatform.standardGlobals();
LuaClosure closure = new LuaClosure(prototype, globals);
closure.invokemethod("something", CoerceJavaToLua.coerce("Foo"));
Run Code Online (Sandbox Code Playgroud)
这会导致invoke方法行出现异常:
org.luaj.vm2.LuaError:尝试索引?(函数值)
谢谢你的帮助!
hjp*_*r92 -1
自从您收到
org.luaj.vm2.LuaError:尝试索引?(函数值)
作为你的错误;这意味着您的函数根本没有被创建。
尝试\n在变量中不加空格并给出空格script。像这样:
String script = "function something(argument) " +
" test_string = 'Hello World!'; " +
" print( test_string ); " +
" print( argument ); " +
" end";
Run Code Online (Sandbox Code Playgroud)