LuaJ - 在Java中创建Lua函数

问题描述:

有没有办法在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(); 
    

在这种情况下,输出会:“来自对方的你好!”

尝试使用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(); 
}