Lua Intermediate: OOP, Closures & Patterns

Lesson 2 of 5

Object-Oriented Lua: Classes and Inheritance

The Fundamentals course showed how setmetatable and __index turn a plain table into something like an instance. Here we build a full class hierarchy with inheritance.

A base class

Lua

Inheriting from it

Lua

Two __index links are at work: Dog's metatable points __index at Animal, so a Dog instance whose class table (Dog) doesn't have a method falls through to Animal. Because Dog:speak is defined, it wins over Animal:speak, this is how overriding works.

Calling the parent's method

Lua

Calling Animal.speak(self) directly (dot syntax, explicit self) is how Lua does "super.method()" calls, there's no dedicated super keyword.

TIP

This two-metatable pattern (class table linked to a parent class table, instances linked to their class table) is the idiomatic way OOP frameworks implement inheritance under the hood, now you know exactly what they're doing for you.

📝 OOP & Inheritance Quiz

Passing score: 70%
  1. 1.To call a parent class's overridden method from a subclass, you...

  2. 2.Overriding Animal:speak with Dog:speak means Dog instances no longer have access to Animal's version unless explicitly called.

  3. 3.The metamethod that makes a missing method lookup fall back to another table is ____.