As I mentioned previously, I’ve been working with Lua recently. I’m really enjoying it. I’d place Lua somewhere slightly to the right of Tcl on my Programming Language Complexity Chart, which probably explains why I found it so immediately appealing.
There are many kinds of simplicity. I think that one of Lua’s strong points is that it tries to get the most possible mileage out of each language feature. For example: Lua is dynamically typed, meaning that values have a type, but any variable can hold a value of any type. Lua defines the following value types:
For purposes of this discussion, we’re going to ignore the userdata type, since that’s mostly used when dealing with opaque data from the “host” program (Lua being designed to be used as an embeddable interpreter).
Now, this is obviously more types than some other scripting languages, but it’s still a fairly short list. Most of the types are fairly self-explanatory – number represents a numeric value, strings are used for text, booleans are used for true and false, nil is the value of an uninitialized variable, and function represents a function.
Tables are an interesting case. Tables are Lua’s implementation of the Associative Array, everybody’s (or at least my) favorite universal data structure. Once you’ve got a data structure that can index arbitrary values with arbitrary keys, you can use it for all sorts of things – and Lua does. As the book Programming in Lua puts it:
Tables in Lua are not a data structure; they are the data structure.
Tables are used to implement records, arrays, Object-Oriented Programming features, namespaces (the package system), and a variety of other features. Even global variables are implemented as entries in a table.
One extremely powerful feature of Lua is metatables, which are tables that affect the behavior of other tables. Every table can have a metatable attached to it, which controls the behavior of the table when certain operations are perfomed on it. This is conceptually similar to operator overloading in C++, but again just implemented as a series of entries in a table.
People have implemented both class-based and prototype-based OOP systems for Lua using just a few relatively simple functions that manipulate tables and metatables. That’s a pretty good example of the power that’s available.
Leave a Reply