Lua Object-Oriented Programming
Lua has no class keyword, but tables, functions and metatables give you everything you need for objects. The usual pattern: a class is a table of methods, each object is a table of data, and the object's metatable sends missing keys (the methods) to the class through __index.
local Account = {}
Account.__index = Account
function Account.new(owner, balance)
local self = setmetatable({}, Account)
self.owner = owner
self.balance = balance or 0
return self
end
function Account:deposit(amount)
self.balance = self.balance + amount
end
function Account:report()
return self.owner .. " has " .. self.balance
end
local acct = Account.new("Nia", 100)
acct:deposit(25)
print(acct:report())Nia has 125
The colon: self
The colon is just syntax sugar for passing the object as the first argument, named self:
| Written | Means |
|---|---|
function Account:deposit(amount) |
function Account.deposit(self, amount) |
acct:deposit(25) |
acct.deposit(acct, 25) |
local Counter = {}
Counter.__index = Counter
function Counter.new() return setmetatable({ n = 0 }, Counter) end
function Counter:inc() self.n = self.n + 1; return self end
local c = Counter.new()
c:inc()
Counter.inc(c) -- the same call, written out
c:inc():inc() -- returning self allows chaining
print(c.n)
print(pcall(function() return c.inc() end)) -- forgot the colon: self is nil4
false /app/output.s:4: attempt to index a nil value (local 'self')
Mixing up . and : is the most common Lua OOP bug. The error "attempt to index a nil value (local 'self')" almost always means a method was called with a dot.
Many objects, one set of methods
Each object stores only its own data; the methods live once in the class table:
local Point = {}
Point.__index = Point
function Point.new(x, y) return setmetatable({ x = x, y = y }, Point) end
function Point:distanceTo(other)
return math.sqrt((self.x - other.x) ^ 2 + (self.y - other.y) ^ 2)
end
function Point:__tostring() return "Point(" .. self.x .. ", " .. self.y .. ")" end
local home, shop = Point.new(0, 0), Point.new(6, 8)
print(home, shop)
print(home:distanceTo(shop))
print(rawget(home, "distanceTo"), getmetatable(home) == Point)Point(0, 0) Point(6, 8)
10.0
nil true
Because Point is also the metatable, metamethods such as __tostring can be defined right in the class.
Class-level data and constants
Fields in the class table are shared by all objects. Instance fields with the same name shadow them:
local Dog = { species = "Canis familiaris", count = 0 }
Dog.__index = Dog
function Dog.new(name)
Dog.count = Dog.count + 1
return setmetatable({ name = name }, Dog)
end
function Dog:speak() return self.name .. " says woof" end
local rex, fido = Dog.new("Rex"), Dog.new("Fido")
fido.speak = function(self) return self.name .. " says WOOF!" end -- per-object override
print(rex:speak())
print(fido:speak())
print(rex.species, Dog.count)Rex says woof
Fido says WOOF!
Canis familiaris 2
Making the class callable
With a __call metamethod on the class itself, you can write Point(1, 2) instead of Point.new(1, 2):
local Temperature = {}
Temperature.__index = Temperature
setmetatable(Temperature, {
__call = function(cls, celsius) return setmetatable({ c = celsius }, cls) end,
})
function Temperature:fahrenheit() return self.c * 9 / 5 + 32 end
local t = Temperature(25)
print(t:fahrenheit())77.0
Privacy
Fields in an object table are public. Lua culture usually accepts that and marks "private" fields with an underscore (self._cache). When you need real privacy, use closures instead of tables for state (see the closures lesson): the data lives in upvalues that only the methods can reach.
Test yourself
What does obj:method(1) mean?
obj.method(1)obj.method(obj, 1)method(obj)obj[method](1)
Why set Class.__index = Class?
- To make the class read-only
- So objects whose metatable is
Classfind missing keys (the methods) inClass - To enable
+on objects - To count the instances
You get "attempt to index a nil value (local 'self')". What is the likely cause?
- The class has no metatable
- A method was called with
.instead of: - The object was garbage collected
selfis a reserved word