Understanding Lua Metatables
The Lua programming language does not have a class-based object oriented system in its definition. Lua metatables are the most common way of implementing such a system, and is analygous in usefulness to method_missing in Ruby or __getattr__ in Python.
Lua Tables
A table in Lua is a way to associate values with keys of values. By allowing generic association, the table can be used both as an array of values indexed by number, or a structure more resembling HashMaps in other languages, where values are indexed by string, or by another value type.
There are several ways to instantiate a table:
1 | t={5, 3, y="blah", 4, x="stuff"} |
Or:
1 | t={} |
Or:
1 | t={} |
In the first case, all unkeyed values are inserted into number indexes by default in the order they appear. The keyed values are indexed by key and not by number.
Table Methods
To create a function value in a table, you can use the following syntax:
1 | t={} |
Or to make it a method that passes self:
1 | t={} |
Note that functions in Lua are values that can be assigned to variables.
Metatables, Finally
Let’s start with some code to think through (pulled from https://www.lua.org/pil/13.html):
1 | t={} |
So any table can be set as the metatable of another table. The metatable describes the behavior of a table by exposing what members of the table are available to access. By adding __add, __mul, __sub, __div, __unm, __pow, __concat, __lt, __le
For example:
1 | Vec = {} |