Metatables, Metamethods, classes and objects in Lua
Archive - Originally posted on "The Horse's Mouth" - 2014-03-18 10:33:44 - Graham EllisIn Lua, almost everything (!) is held as a table. You don't have lists, hashes, dicts, arrays, objects, namespaces - you have tables. It helps consistency, in helps keep the language small - but at times it does mean you have to be a little bit more aware of how the features of tables can be combined to use the feature set in a chosen way.
Lets take tables as objects. Here's a suggestion:
- Definitions
* Put all your funtion(allity) into a table who's name is the class name
* first parameter of the object method functions to be the object/data table
* Have a function in there called "new" as your constructor
* Have a metatable which points to the class table for its methods
- creating objects
* Have your constructor create a local table of attributes
* Also have your constructor point to the metatable
* your constructor shoudl return the local table
- calling object methods
* defined as functions in the table for the class
* call them by "object.method(object, ...)" syntax
* or use the "object:method(...)" syntax, provided to make it easier
If you want to overload the operators for your table type (class) you can even to that in your metatable. The following are the methods you may define - in each case starting with __. And you may also provide a "tostring" method which controls how the table's to be printed out if you just say "print (mytable}":
function | when it's used |
add | + |
call | run as function |
concat | .. |
div | / |
eq | == |
index | catch all -> (direct back to self) |
le | <= |
len | # |
lt | < |
mod | % |
mul | * |
newindex | add element to table |
pow | ** |
sub | - |
unm | - (unary) |
There's an example of much of this in an example I wrote on the Lua course earlier this week, teaching Lua in Glasgow. Very rarely do you use every feature in a short demonstration, so some of the timing above aren't illustrated. However, there are plenty of other examples in our Towards OO in Lua resources. Full source of the example is [here].