Hi folks, this post aims to offer a clear introduction to the topic of metatables in Lua for those who are not yet familiar with them. I originally wrote this for the forums of PICO-8, a ‘fantasy console’ with limitations inspired by classic 8-bit computers, which uses a modified flavour of Lua 5.2.
Without further ado, let’s go!
A table is a mapping of keys to values. They’re explained quite well in the PICO-8 manual and the Lua reference manual so I won’t go into more detail. In particular you should know that t.foo
is just a nicer way of writing t["foo"]
and also that t:foo()
is a nicer way of calling the function t.foo(t)
A metatable is a table with some specially named properties defined inside. You apply a metatable to any other table to change the way that table behaves. This can be used to:
- define custom operations for your table (+, -, etc.)
- define what should happen when somebody tries to look up a key that doesn’t exist
- specify how your table should be converted to a string (e.g. for printing)
- change the way the garbage collector treats your table (e.g. tables with weak keys)
Point #2 is especially powerful because it allows you to set default values for missing properties, or specify a prototype object which contains methods shared by many tables.
You can attach a metatable to any other table using the setmetatable function.
All possible metatable events are explained on the lua-users wiki:
>>> list of metatable events <<<
which is, as far as I’m aware, the best reference for everything that metatables can be used for.
And that’s really all you need to know!