I have to bind an Objective-C object to a variable of a Lua script. I don't have write access to this Lua script, I just load and run it from the Objective-C code. I know it uses a variable, called luaVar
, that uses methods defined in the object. Here is the Lua code:
function run()
print("Running Lua script")
print(luaVar)
print("Ending Lua script")
end
run()
This script should print the luaVar
variable, and not nil
. Now, here is the Objective-C code I use. The function validate
gets the Lua code in the script
variable and the object to pass to Lua as f
in the theObject
variable:
#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;
}
I tried the approach from this SO answer, but that didn't handle Objective-C objects. I looked at this question, but it is not clear how it does the binding.
Does anyone know how to do that?