我必须将Objective-C对象绑定到Lua脚本的变量。我没有对这个Lua脚本的写访问权限,我只是从Objective-C代码加载并运行它。我知道它使用一个名为luaVar
的变量,它使用对象中定义的方法。这是Lua代码:
function run()
print("Running Lua script")
print(luaVar)
print("Ending Lua script")
end
run()
此脚本应打印luaVar
变量,而不是nil
。现在,这是我使用的Objective-C代码。函数validate
获取script
变量中的Lua代码和f
变量中theObject
传递给Lua的对象:
#import "ScriptObject.h"
static const char* SCRIPT_OBJECT_LUA_KEY = "f";
ScriptObject* scriptObject = nil;
- (void)validate:(NSString*)script withObject:(ScriptObject*)theObject {
L = luaL_newstate(); // create a new state structure for the interpreter
luaL_openlibs(L); // load all the standard libraries into the interpreter
lua_settop(L, 0);
newScriptObject(L);
// load the script
int err = luaL_loadstring(L, [script cStringUsingEncoding:NSASCIIStringEncoding]);
if (LUA_OK != err) {
NSLog(@"Error while loading Lua script!");
lua_pop(L, 1);
return NO;
}
// call the script
err = lua_pcall(L, 0, LUA_MULTRET, 0);
if (LUA_OK != err) {
NSLog(@"Error while running Lua script: %s", lua_tostring(L, -1));
lua_pop(L, 1);
return NO;
}
lua_close(L);
}
static int newScriptObject(lua_State *L) {
ScriptObject * __strong *lgo = (ScriptObject * __strong *)lua_newuserdata(L, sizeof(ScriptObject *));
*lgo = scriptObject;
luaL_getmetatable(L, SCRIPT_OBJECT_LUA_KEY);
lua_setmetatable(L, -2);
lua_newtable(L);
lua_setuservalue(L, -2);
NSLog(@"New ScriptObject created");
return 1;
}
我尝试了this SO answer的方法,但是没有处理Objective-C对象。我查看了this question,但目前尚不清楚它是如何进行绑定的。
有谁知道怎么做?
答案 0 :(得分:0)
自己找到它。它只是newScriptObject
函数末尾的缺失行,它将已定义的变量设置为Lua全局:
lua_setglobal(L, SCRIPT_OBJECT_LUA_KEY);