Model objects and inheritance with Lua metatables
8 steps · about 1 h 42 min · Intermediate
- Read the metatables and metamethods rules in the Lua 5.4 manual (reference, Lua.org, 20 min)
The authoritative list of every metamethod and when Lua calls it.
- Overload arithmetic with metamethods (tutorial, Programming in Lua, 10 min)
Builds a set type that adds and multiplies with + and *.
- Give tables default values through __index (tutorial, Programming in Lua, 8 min)
Shows the smallest useful __index trick and its memory trade-offs.
- Track every table read and write with a proxy (tutorial, Programming in Lua, 10 min)
Combines __index and __newindex to watch access to a table.
- Turn a table and its metatable into a class (tutorial, Programming in Lua, 12 min)
Introduces the self parameter and the colon call syntax for methods.
- Inherit and override methods in a subclass (tutorial, Programming in Lua, 12 min)
Chains __index lookups so a subclass reuses and replaces parent methods.
- Run through every metamethod with examples (article, lua-users wiki, 15 min)
Community examples for __call, __tostring, __eq, __lt and friends.
- Compare object patterns used in real Lua code (article, lua-users wiki, 15 min)
Contrasts metatable classes with closure-based objects so you can choose.