javalualuaj

LuaJ - Creating a Lua function in Java


Is there a way to create a Lua function in Java and pass it to Lua to assign it into a variable?

For example:

In this case, the output would be: "Hello from the other side!"


Solution

  • Try using Globals.load() to construct a function from a script String, and use LuaValue.set() to set values in your Globals:

    static Globals globals = JsePlatform.standardGlobals();
    
    public static class DoSomething extends ZeroArgFunction {
        @Override
        public LuaValue call() {
            // Return a function compiled from an in-line script
            return globals.load("print 'hello from the other side!'");
        }
    }
    
    public static void main(String[] args) throws Exception {
        // Load the DoSomething function into the globals
        globals.set("myHandler", new LuaTable());
        globals.get("myHandler").set("doSomething", new DoSomething());
    
        // Run the function
        String script = 
                "myVar = myHandler.doSomething();"+
                "myVar()";
        LuaValue chunk = globals.load(script);
        chunk.call();
    }