Menu

Passing arguments to a Lua function with Luaj

Anonymous
2013-02-04
2014-02-05
  • Anonymous

    Anonymous - 2013-02-04

    Hey guys

    I have kind of a newbie question here, but I couldn't find an answer anywhere so far. I posted it on Stackoverflow: http://stackoverflow.com/questions/14504300/passing-arguments-to-a-lua-function-with-luaj

    It would be awesome to get some help here!

    Thanks!

     
  • James Roseborough

    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.

     
  • David Ryan

    David Ryan - 2014-02-05

    Is it possible to set variables in Lua from Java? For instance:

    String script = "print(a)";
    InputStream is = new ByteArrayInputStream(script.getBytes());
    Globals globals = JsePlatform.standardGlobals();
    Prototype p = globals.compilePrototype(is, "script");
    LuaClosure f = new LuaClosure(p,globals);
    // set variable a here?
    f.invoke();

    I tried f.set("a","test");

    However, got the error:

    org.luaj.vm2.LuaError: index expected, got function

    Thanks,
    David.

     

Log in to post a comment.