Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to a lua function with luaj

Tags:

java

lua

luaj

I'm trying to call a lua function in a Java program using LuaJ. It works fine when I'm not passing any arguments 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 takes an argument and I just can't figure out how to pass in the argument from Java. Here's what I 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, "script");
LuaValue globals = JsePlatform.standardGlobals();
LuaClosure closure = new LuaClosure(prototype, globals);
closure.invokemethod("something", CoerceJavaToLua.coerce("Foo"));

This results in an Exception on the invokemethod line:

org.luaj.vm2.LuaError: attempt to index ? (a function value)

Thanks for your help!

like image 469
nerdinand Avatar asked Oct 21 '22 19:10

nerdinand


1 Answers

In lua, the top-level scope is an anonymous function with variable arguments. These are accessed using ... In your example, you don't need the function named something, the chunk itself can be used as an unnamed function.

For example, this code in 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") );

Produced this result for me:

Hello World!
some-arg-value

You can pass in any number of arguments this way.

like image 195
Jim Roseborough Avatar answered Oct 24 '22 16:10

Jim Roseborough