Java – use luaj to pass parameters to Lua functions
•
Java
I'm trying to use LuaJ to call Lua function in Java program. It works when I don't pass any parameters to the closure:
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();
But now I'm trying a Lua script with a top-level function that accepts a parameter, and I can't figure out how to pass in parameters from Java That's what I've got so far:
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"));
This causes an exception in the invoke method line:
Thanks for your help!
Solution
In Lua, the top-level scope is an anonymous function with variable parameters These are accessed using In your example, you don't need a function named something. The block itself can be used as an unnamed function
For example, this code is in luaj-3.0-beta 1
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") );
Made this result for me:
Hello World! some-arg-value
You can pass any number of parameters in this way
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码