Model objects and inheritance with Lua metatables

8 steps · about 1 h 42 min · Intermediate

  1. 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.

  2. Overload arithmetic with metamethods (tutorial, Programming in Lua, 10 min)

    Builds a set type that adds and multiplies with + and *.

  3. Give tables default values through __index (tutorial, Programming in Lua, 8 min)

    Shows the smallest useful __index trick and its memory trade-offs.

  4. 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.

  5. 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.

  6. Inherit and override methods in a subclass (tutorial, Programming in Lua, 12 min)

    Chains __index lookups so a subclass reuses and replaces parent methods.

  7. Run through every metamethod with examples (article, lua-users wiki, 15 min)

    Community examples for __call, __tostring, __eq, __lt and friends.

  8. 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.