Lua does not have a native class keyword. Instead, it utilizes Prototype-Based Object Orientation (similar to JavaScript's underlying prototype chain). Every class is simply a prototype table, and instances are tables whose __index points to that prototype.
The Colon Method Syntax (:)
The colon syntax is syntactic sugar that automatically binds the calling object to the first parameter named self:
local Account = { balance = 0 }
-- Defining with colon:
function Account:deposit(amount)
self.balance = self.balance + amount
end
-- EXACTLY equivalent to defining with dot and explicit self:
function Account.deposit(self, amount)
self.balance = self.balance + amount
end
-- Invoking with colon implicitly passes the caller as 'self':
Account:deposit(100)
-- Equivalent to:
Account.deposit(Account, 100)
Classical Class Construction Pattern
local Monster = {}
Monster.__index = Monster
-- Constructor
function Monster:new(species, health, attackPower)
-- 'self' refers to the Monster class table when invoked as Monster:new()
local instance = setmetatable({}, self)
instance.species = species
instance.health = health
instance.attackPower = attackPower
return instance
end
function Monster:attack(target)
print(string.format("%s attacks %s for %d damage!", self.species, target.name, self.attackPower))
end
-- Create instance
local goblin = Monster:new("Goblin", 30, 8)
local targetDummy = { name = "Training Dummy" }
goblin:attack(targetDummy)
Subclassing & Single Inheritance
To inherit from a class, create a new class table whose metatable's __index points to the parent class:
-- Dragon inherits from Monster
local Dragon = setmetatable({}, { __index = Monster })
Dragon.__index = Dragon
function Dragon:new(species, health, attackPower, breathElement)
-- 1. Call parent constructor
local instance = Monster.new(self, species, health, attackPower)
-- 2. Add subclass-specific properties
instance.breathElement = breathElement or "Fire"
return instance
end
-- Override parent method
function Dragon:attack(target)
print(string.format("%s unleashes a devastating %s breath on %s for %d damage!",
self.species, self.breathElement, target.name, self.attackPower * 2))
end
-- Subclass-specific method
function Dragon:fly()
print(self.species .. " takes to the skies!")
end
local smaug = Dragon:new("Smaug", 2500, 150, "Inferno Fire")
smaug:fly()
smaug:attack(targetDummy) -- Calls overridden method!
Exercises
- Create a
BankAccountbase class and anInterestCheckingAccountsubclass that applies a 2% monthly interest rate. - Implement polymorphism: create an array of different
Shapesubclasses (Circle,Rectangle) and calculate total area in a single loop. - Explain why
instance:method()fails ifClass.__index = Classwas omitted during class definition.