I’ve blogged in the past about the LuaObjCBridge and my affection for it. I kept meaning to post some code about it but I never got around to it. Today, Gus Mueller released LuaCore, his Objective-C wrapper around LuaObjCBridge. I figure I’ll go ahead and toss my code out as well.
Gus’s wrapper and my wrapper do many similar things but are quite different. His is more framework-y. It’d probably be a better choice for people who need more control. Mine is geared towards convenience. I wrote it to make things more convenient and only wrote methods that I needed. Gus’s comes packaged up, ready to be dropped into an application. Mine needs to be paired with LuaObjCBridge (but it’s as simple as dropping my files in after setting up the framework).
More information on using my Lua wrapper is available in the extended entry.
LuaEnv may look a bit odd at first but it suits different workflows. Different parts were written for different uses. For this reason, there isn’t a unified or consistent style. It just does what I needed it to do. If you just want to be able to run lua files, +(NSError *)runLuaFileNamed:withParametersWithNames: should do what you need. If you need a bit more, LuaEnv should handle most of your needs.
First, you need to import LuaEnv. If you’ve got LuaObjCBridge setup, simply drop LuaEnv.h/m into your project and import them into whatever file you want using the standard import "LuaEnv.h". Now you can start working with it.
LuaEnv *L = [LuaEnv instance];
NSDictionary *d = [NSDictionary dictionaryWithObject:@"object" forKey:@"key"];
[L addGlobalObject:d withName:@"dict"]; // Adds a global parameter named "dict"
The above starts a lua environment and adds a global parameter. Good stuff. Now, you can run a file.
NSString *path = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"lua"]];
[L runFile:path]; // Loads and executes the file
[L run]; // Hell, let's run it again for kicks.
runFile: will load the file and run it. Alternatively, you can use loadFile: and then run. There may be times that you want to load a file but not run it right then. You can also call functions in a lua file by using callFunction:withParameters:. Note that a file is run (by necessity, the environment can’t find the function until the file’s been processed) when using callFunction:withParameters.
[L callFunction:@"someFunction" withParameters:[NSArray arrayWithObjects:@"firstParam", @"secondParam", nil]];
If you don’t need much control over everything, LuaEnv has a handy convenience method that lets you run a file in your bundle.
NSError *err = [LuaEnv runLuaFileNamed:@"luaFile" withGlobalObjectsWithNames:dict, @"aDictionary", @"a standard string", @"stringObject", nil];
if (err) NSLog(@"%@", err);
Leave a Reply