Uncommon Lua Features: Coroutines
Last week I talked about how to use Cocoa notifications to connect a Lua environment to a Cocoa UI. This is great for things like this:
When the user clicks a space on the map containing a unit, update the status panel with the specs for that unit
But terrible for things like this:
When the user clicks OK, load the next level out of the level file and send it to a Lua function for pre-processing
Things like that are even more common than the first type, but result in terrible code. What to do?
Handling Cocoa Notifications With Lua
This is less a “cool Lua trick” and more a “cool way to use Lua”. What I’m doing is using Lua to write a Cocoa application. There are a couple tools to do this (Wax and LuaCore spring to mind) but they work on a different paradigm: they’re like RubyCocoa in that they have a bridge where you can write Lua code that makes Cocoa objects, and write your whole app in Lua. I don’t want to do that because I don’t want to get in a race with Apple. Cocoa has a pretty good Objective C interface, including stuff like blocks and Interface Builder and CoreAnimation, and I’m perfectly happy to use it. I would just prefer to write the parts of my program that aren’t tied to Cocoa objects in something a little more terse.
Making Lua Look Like Prolog
Lua, like most languages, has some object-oriented pieces. But, it doesn’t have classes and modules and objects: it takes the Scheme approach and gives you the tools you need to build the OO paradigm you want to use. In particular, the only data structure it gives you is called a table and is essentially a hashtable married to an array (it’s a hashtable, but it has accelerated access for integer keys, so it’s efficient to use for either one). Tables can be assigned metatables which define special behavior for the table: if you try to access a key that doesn’t exist, it looks in the metatable for “__index” and uses that to find what the value should be.
But if all that was intended was to make it easy to duplicate class-based OO, Lua would just have put in class-based OO, right? Let’s try something different, that uses this same trick to do something cool. Let’s make Lua look like Prolog.