LuaJ - Создание функции Lua в Java

Есть ли способ создать функцию Lua в Java и передать ее Lua, чтобы присвоить ее переменной?

Например:

  • В моем классе Java:

    private class doSomething extends ZeroArgFunction {
        @Override
        public LuaValue call() {
            return "function myFunction() print ('Hello from the other side!'); end" //it is just an example
        }
    }
    
  • В моем сценарии Lua:

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

В этом случае вывод будет: "Привет с другой стороны!"

1 ответ

Решение

Попробуйте использовать Globals.load() для создания функции из сценария String и используйте 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();
}
Другие вопросы по тегам