我正在使用LuaJ 3.0编写安卓应用程序。如何将我的Java对象绑定到特定的LuaClosure(用于整个脚本)?
Lua代码:
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();我知道在Global2.0(但不是3.0)中有LuaValue.setenv,我还知道如何创建库并将它们绑定到LuaJ。
发布于 2013-05-29 18:36:20
从API3.0开始,修改闭包的功能从LuaJ中删除了。如果只想将Java对象绑定到特定Lua环境,可以创建多个Globals。然后,您可以将Java对象绑定到特定的Globals,并从每个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是最好的选择。
https://stackoverflow.com/questions/14223219
复制相似问题