Lua: Metatable OOP

Lua has long been hailed as a very flexible language that allows programmers to create features they need from it even if those features do not exist by default. One such notable feature is an object-oriented paradigm that can be implemented in Lua using metatable manipulations. By request of friends, this post will give some basic insight into how this is done.

Lua’s metatables are special tables that can be assigned to objects to dictate their behaviour. Metatables are primarily geared towards changing the behaviour of tables, making them into more than just sophisticated storage mechanisms and making them able to perform other functions (although metatables can also be used to change the behaviour of strings—this is a separate topic).

Metatables have a specific format—specific key-value pairs that are used to define, or redefine, behaviour. One such pair, one that could be said to be used most, is __index. It allows to add or change tables that are used to look up fields. For instance: suppose you have an empty table tbl. If you try to index the field a, you will find it to be nil. However, by setting the metatable of tbl to such that the __index table contains the field a, Lua will also look the field up in that table, and any tables that table has as indexes, until it fails and returns nil. In code:

With this knowledge, we can create a dead simple OOP architecture, an almost prototype-based one, using just two functions (one of which will be a helper):

Admittedly, this is a trivial example, but with a little creativity this could be extended to encompass inheritance and other OOP tenets. There are also OOP libraries with different feature sets for different kinds of projects—especially deserving of mention are 30log and MiddleClass.

Published by

avatar

EngiN33R

Developer, human and programming language enthusiast, teacher at heart. Please remember: all my opinions are independent and subjective.

Leave a Reply

Your email address will not be published.