2016-01-22 33 views
0

有沒有辦法在Java中創建Lua函數並將其傳遞給Lua以將其分配給變量?LuaJ - 在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()來構造從腳本字符串的函數,並使用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(); 
}