我正在尝试使用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();
但是现在我正在尝试一个带有顶级函数的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,globals); closure.invokemethod("something",CoerceJavaToLua.coerce("Foo"));
这会导致invoke方法行出现异常:
org.luaj.vm2.LuaError: attempt to index ? (a function value)
谢谢你的帮助!
解决方法
在lua中,顶级作用域是具有可变参数的匿名函数.这些是使用…访问的.在您的示例中,您不需要名为something的函数,块本身可以用作未命名的函数.
例如,这个代码在luaj-3.0-beta1中
String script = "argument = ...\n"+ "test_string = 'Hello World!'\n"+ "print(test_string)\n"+ "print(argument)\n"; Globals globals = JsePlatform.standardGlobals(); LuaValue chunk = globals.loadString(script,"myscript"); chunk.call( LuaValue.valueOf("some-arg-value") );
为我制作了这个结果:
Hello World! some-arg-value
您可以通过这种方式传递任意数量的参数.