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!"

4

1 回答 1

1

尝试使用 Globals.load() 从脚本字符串构造函数,并使用 LuaValue.set() 设置全局值:

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();
}
于 2016-01-23T03:27:23.987 回答