Single Inheritance with __index Chaining
Set a parent class as a metatable's __index to inherit methods.
Prototype Chain
Single inheritance works by setting a child class's __index to the parent class. When a method is not found in the child, Lua looks in the parent. This creates a prototype chain.
local Base={}
Base.__index=Base
function Base.new() return setmetatable({},Base) end
function Base:greet() print("Hello from Base") end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base}) -- Child inherits Base
function Child.new() return setmetatable({},Child) end
local c=Child.new()
c:greet() -- Hello from Base (inherited)Method Resolution Order
When calling a method on an instance: (1) look in instance table, (2) look in Child (via __index), (3) look in Base (via Child's metatable __index). The first match wins.
local Base={}
Base.__index=Base
function Base:who() print("I am Base") end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base})
function Child:who() print("I am Child") end -- override
local b=setmetatable({},Base)
local c=setmetatable({},Child)
b:who() -- I am Base
c:who() -- I am Child (overrides)All lessons in this course
- Single Inheritance with __index Chaining
- Calling Parent Methods with super
- Mixin Patterns
- Overriding and Polymorphism