Big Bucket Software you like to use
Lua is good
March 7th, 2006

Y’know, I quite like Lua. It’s not the same reaction I got when I started to learn/discover Ruby, that was something else. Learning Lua feels more like learning OpenGL or assembly even; the joy is in the low-level API. When I say “learning Lua” I mean learning how to interface it from C. This morning I looked up the reference manual to see how I might call a function defined in Lua from C. My immediate reaction was, “Gee, that’s easy.”

The integration with Mage is really coming along well; I’m already using Lua to load in my Image and Animations. In fact, it’s a heck of a lot quicker than my previous method. Allow me a minute to explain that method:

Previously, I had this sort of recursive typeless-type, similar to Qt’s QVariant or Boost’s any. I had functions that took in one of these ‘Containers’, validated that it contained the relevant keys, (e.g. in the case of Image, it would look for filename and transparency key) and produced an object. These objects would then go into a library. The function that created Animations from containers would then need the Image library in order to locate an Image referred to by name. Just as an the function responsible for creating ActorViews needed the Animation library. This process soon became very slow, it was O(n) every time an object needed to be retrieved from the library.

Now, in my Lua script, I can make a call like this:

img  = Image.new("walrus.png")
anim = Animation.new()
anim:insertFrame(img)

Both img and anim are tables containing a “ptr” key. This key contains a pointer to the C++ object on the heap. Meaning that adding an Image to an Animation is a O(1), just dereference the pointer! I know I shouldn’t be emphasizing the speed benefit as this is really about up-front configuration, but I must say, this new approach is much quicker. It is also much less error-prone; in the old method, it was possible to mistype the name of an object and end up with not being able to locate something in a library. With this new method, it looks like I might be able to get rid of the library’s altogether, but small steps, small steps.

Another thing – the reason I’m looking into call lua functions from C, is for my message-passing mechanism. See here for more information. Real soon now, I’m going to make some modifications to the Messenger so that a signal can be slotted to a Lua function. This really simplifies the underlying engine code, no need to set/unset flags, pass parameters etc. I’m eager to see how it turns out.

I’ve been very incoherent here, mostly because I don’t have a coherent point, suffice to say that Lua has been an interesting learning experience and I’m slowly becoming more confident with its abilities.