LuaJ - 在 Java 中创建一个 Lua 函数
LuaJ - Creating a Lua function in Java
有没有办法在 Java 中创建一个 Lua 函数并将其传递给 Lua 以将其分配给一个变量?
例如:
在我的Javaclass:
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!"
尝试使用 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();
}
有没有办法在 Java 中创建一个 Lua 函数并将其传递给 Lua 以将其分配给一个变量?
例如:
在我的Javaclass:
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!"
尝试使用 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();
}