0

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 my Java class:

    private class doSomething extends ZeroArgFunction {
        @Override
        public LuaValue call() {
            return "function myFunction() print ('Hello from the other side!'); end" //it is just an example
        }
    }
    
  • In my Lua script:

    myVar = myHandler.doSomething();
    myVar();
    

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

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.