【问题标题】:LuaJ - Creating a Lua function in JavaLuaJ - 在 Java 中创建 Lua 函数
【发布时间】:2016-04-29 00:06:51
【问题描述】:

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

在这种情况下,输出将是:“来自另一边的你好!”

【问题讨论】:

    标签: java lua luaj


    【解决方案1】:

    尝试使用 Globals.load() 从脚本字符串构造一个函数,并使用 LuaValue.set() 在你的 Globals 中设置值:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 2012-06-30
      • 2016-05-25
      • 2019-10-12
      • 1970-01-01
      • 2013-06-04
      • 2013-01-08
      • 2015-12-12
      • 2014-10-22
      相关资源
      最近更新 更多