【问题标题】:How to excute a Lua compiled file and call functions with custom global environment in LuaJ?如何在 LuaJ 中使用自定义全局环境执行 Lua 编译文件并调用函数?
【发布时间】:2016-10-20 15:22:40
【问题描述】:

我已经用 ScriptEngine 预编译了 Lua 脚本。

private void preCompile(){
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("luaj");
    if(engine instanceof Compilable){
        try {
            compScript = ((Compilable)engine).compile(scriptContent);
        }catch (ScriptException se){
            System.err.println(se.getMessage());
        }
    }else{
        System.err.println("Engine can't compile code!");
    }

我也可以使用 eval() 函数执行它,并使用 LuaFunction.invoke(LuaValue) 调用脚本中的函数。

public Object callFunction(String funcName, Object[] args){
    preCompile();
    Bindings script_bindings = new SimpleBindings();
    try{
        compScript.eval(script_bindings);
        LuaFunction luafunc = (LuaFunction)script_bindings.get(funcName);
        LuaValue[] luaValues = new LuaValue[args.length];
        for(int i = 0; i < args.length; ++i){
            luaValues[i] = CoerceJavaToLua.coerce(args[i]);
        }
        result = luafunc.invoke(luaValues);
    }catch (ScriptException se){
        System.out.println(se.getMessage());
    }
    return result;
}

问题来了:

我可以使用 Java API 执行脚本,但我想做的是使用 Global 创建自定义环境。

所以我创建全局对象并像这样加载所需的库:

private void LoadScript(){
    globals = new Globals();
    globals.load(new JseBaseLib());
    globals.load(new PackageLib());
    globals.load(new StringLib());
    globals.load(new Bit32Lib());
    globals.load(new TableLib());
    LoadState.install(globals);
    LuaC.install(globals);

现在我只是不知道如何将“全局变量”链接到编译文件(compScript)。我试过全局编译函数

Prototype chunk = globals.compilePrototype(new StringReader(script), "script");

chunk.call() 可用于执行脚本,但我仍然不知道如何在我的自定义“全局”环境中通过“块”或“compScript”调用脚本中的函数(带或不带参数)。

另外,globals.load()函数是编译脚本文件吗?我只想编译一次脚本并重用它。

【问题讨论】:

  • 你看到invokemethod 接受函数名的方法了吗?

标签: java lua precompiled luaj


【解决方案1】:

必须使用globals.load 获取块。然后你可以call 块并从全局获取你想要的 lua 函数,假设你的函数被定义为全局的。如果是local,则不能使用。

LuaValue chunk = globals.load(script, "script");
chunk.call();
LuaValue func = globals.get(functionName);
func.call(args);

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多