What is a metatable?

Well, I’ve recently become aware of the existence of metatable and this will probably serve me well because of the continued use of tables that I use. However, I have no idea what it is for or how it works.

The best way I can describe metatables is that they’re basically an implementation of operator overloading but in Lua. (e.g: in object-oriented programming languages, like C#, there’s a feature where you can implement operator overloads which enable you to do things like add two objects together, multiply, etc.)

These are done with use of metamethods, which invoke when specific actions on metatables occur.

There’s actually quite a few articles on metatables/metamethods already, I’d recommend checking some of those out. Here’s a reference to the lua documentation: Programming in Lua : 13

Generally people use metatables for object-oriented implementations. (e.g: all created objects still have reference to methods of a class without directly having them as members of itself (the table object))

2 Likes