5

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!

nerdinand
  • 876
  • 12
  • 21

2 Answers2

4

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.

Jim Roseborough
  • 201
  • 1
  • 4
  • your explanation on anonymous function cleared a lot of things. I have another question over you code: can I read the variable defined in LUA script back into JAVA, like the "test_string" variable? – Jerry Tian Mar 03 '14 at 10:15
-1

Since you receive

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

as your error; this means that your function is not being created at all.

Try it without \n and give spaces in the variable script. Like this:

String script = "function something(argument) " + 
        " test_string = 'Hello World!'; " + 
        " print( test_string ); " + 
        " print( argument ); " + 
        " end";
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • That does not seem to be it. I'm getting the exact same error. Also, if the script was not correct somehow, shouldn't the LuaC.compile call already fail? – nerdinand Jan 24 '13 at 16:48