1

我正在使用 LuaJ 3.0 编写 Android 应用程序。如何将我的 Java 对象绑定到特定的 LuaClosure(对于整个脚本)?

卢阿代码:

local  = state or nil
state.foo("some string")

Java代码:

Prototype prototype;

    try{

        InputStream stream = mContext.getResources().getAssets().open(LUA_ASSETS_DIRECTORY + "test.lua");
        prototype = LuaC.compile(stream, "script");

    } catch (IOException e) {

        return false;
    }

    LuaClosure closure = new LuaClosure(prototype, mLuaGlobals);
    // binding code
    closure.call();

我知道在 LuaJ 2.0(但不是 3.0)中有 LuaValue.setenv,而且我知道创建库并将它们绑定到 Globals。

4

1 回答 1

1

从 LuaJ 3.0 开始,修改闭包的能力从 API 中移除。如果您只想将您的 Java 对象绑定到特定的 Lua 环境,您可以创建多个Globals。然后,您可以将您的 Java 对象绑定到特定的 Globals,并从它们中的每一个创建一个闭包:

Globals mLuaGlobals1 = JsePlatform.standardGlobals();
Globals mLuaGlobals2 = JsePlatform.standardGlobals();
Globals mLuaGlobals3 = JsePlatform.standardGlobals();

// binding code
mLuaGlobals1.rawset("state", CoerceJavaToLua.coerce(yourJavaObject));
mLuaGlobals2.rawset("state", CoerceJavaToLua.coerce(anotherJavaObject));
// We don't expose anything to mLuaGlobals3 in this example

// Create closures
// We use exact same prototype (script code) for each of them
LuaClosure closure1 = new LuaClosure(prototype, mLuaGlobals1);
LuaClosure closure2 = new LuaClosure(prototype, mLuaGlobals2);
LuaClosure closure3 = new LuaClosure(prototype, mLuaGlobals3);

closure1.call(); // yourJavaObject is exposed through "state" variable
closure2.call(); // anotherJavaObject is exposed through "state" variable
closure3.call(); // "state" variable is absent

是的,这是一个愚蠢的解决方案,所以如果你真的需要 LuaClosure 的控制,降级到 LuaJ 2.0.3 是最好的选择。

于 2013-05-29T10:36:19.943 回答