将Objective-C对象绑定到现有的Lua变量

时间:2014-01-14 11:56:34

标签: iphone objective-c lua

我必须将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,但目前尚不清楚它是如何进行绑定的。

有谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

自己找到它。它只是newScriptObject函数末尾的缺失行,它将已定义的变量设置为Lua全局:

lua_setglobal(L, SCRIPT_OBJECT_LUA_KEY);