简体   繁体   English

LuaJ-用Java创建Lua函数

[英]LuaJ - Creating a Lua function in Java

Is there a way to create a Lua function in Java and pass it to Lua to assign it into a variable? 有没有办法在Java中创建Lua函数并将其传递给Lua以将其分配给变量?

For example: 例如:

  • In my Java class: 在我的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 } } 
  • In my Lua script: 在我的Lua脚本中:

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

In this case, the output would be: "Hello from the other side!" 在这种情况下,输出将是:“从另一侧打招呼!”

Try using Globals.load() to construct a function from a script String, and use LuaValue.set() to set values in your Globals: 尝试使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM