0

JavaでLua関数を作成し、それを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();
    

この場合、出力は「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 に答える