Lesson 5 of 6
Objects in Luau: metatables, classes, composition
Learn object-oriented programming in Luau for Roblox. The colon and self, metatables and __index, classes, inheritance, composition, and when Roblox games should not use classes at all, with runnable cells and Beacon Yard's drone.
By the end you can
- Call methods with the colon and explain what self is
- Build a class from a table, a metatable and __index, and create independent objects from it
- Choose composition over inheritance, and say when a plain module table is the better design
Before this: Debugging basics: Output, stack traces and breakpoints
1One drone, no class
Later in Beacon Yard, the yard gains a single enemy drone. In the game's source, that drone is just a plain table of fields (model, root, colors, hits, highlight and healthBar) driven by functions on DroneService. Its health and stun time are not table fields: they live as attributes on the drone's root part (Health and StunnedUntil). There is no Drone class, no new, and no metatable anywhere in the server code. This is a simplified sketch of that record, with the health and stun time written as fields to keep the focus on state:
local current = {
health = 100,
maxHealth = 100,
stunnedUntil = 0,
hits = {},
}

Select a numbered pin, or a row below, to read what it marks.
Beacon Yard's drone in action: one plain record, driven by functions on DroneService.
That is a deliberate choice, and by the end of this lesson you will be able to defend it or argue for a class instead. Suppose the design changes to three drones per round, each with its own health and stun timer. Then you want many objects that behave the same way. That is what classes are for.
DroneService keeps the drone in one module-level variable, current. How many drones can exist at once?
Answer
One. current holds one drone table. Functions such as damageFromWrench act on it directly, which is simple because there is only ever one.
Open this step in lesson mode · Link to this step · This confused me
2Methods and self
A methodMethodA function stored on a table that works on that table, called with a colon.Think of it as asking an object to do something to itself. is a function stored on a table that works on that table. Luau has a shortcut for it, the colon. drone:damage(34) means drone.damage(drone, 34): the table itself is passed as the first argument, which the function calls self. Defining with a colon, function Drone:damage(amount), adds that hidden self parameter for you.
You have used the colon on strings and Roblox objects since the first lessons: name:upper(), event:Connect(...). Mixing up colon and dot is one of the most common Luau bugs, because the wrong value lands in self.
local drone = { health = 100 }
function drone:damage(amount)
self.health -= amount
return self.health
end
print(drone:damage(34))
print(drone.damage(drone, 34))
local ok, message = pcall(function()
return drone.damage(34)
end)
print(ok, message)
66
32
false main:3: attempt to index number with 'health'In drone.damage(34), which value lands in self?
function drone:damage(amount)
self.health -= amount
end
drone.damage(34)
Answer
34. Without the colon, the first argument you pass becomes self. self is 34 and amount is nil, so reading self.health fails: you cannot index a number.
Open this step in lesson mode · Link to this step · This confused me
3Metatables: where to look next
Copying every method into every drone table would waste memory and make changes painful. Luau's answer is the metatableMetatableA table attached to another table that changes how it behaves, through keys such as __index and __tostring.Think of it as a note clipped to a card saying where to look for anything not written on it.: a second table attached to the first, holding special keys called metamethods that change how the first table behaves1.
The one you need for classes is __index. When you read a key that a table does not have, Luau checks its metatable's __index. If that is a table, Luau looks the key up there instead. Two built-in functions show it clearly: setmetatable(t, mt) attaches metatable mt to table t (and returns t), and rawget(t, key) reads straight from t without checking __index.
| In the picture | In Roblox |
|---|---|
| The recipe book | The class table that holds the methods |
| Each card | An object made by new, holding its own fields |
| The note: see the book for anything not on this card | The metatable's __index pointing at the class |
A class is a shared recipe book. Each drone is a small card with its own numbers (health, name), and a note on the card says "for anything not written here, see the book".
Think of it as A shared recipe book
local defaults = { health = 100, speed = 12 }
local drone = setmetatable({ name = "Drone1" }, { __index = defaults })
print(drone.name, drone.health, drone.speed)
print(rawget(drone, "health"))
drone.health = 66
print(drone.health, defaults.health)
Drone1 100 12
nil
66 100Open this step in lesson mode · Link to this step · This confused me
4A class in eight lines
Put the colon and __index together and you have the standard Luau class pattern:
local Drone = {}holds the methods.Drone.__index = Dronemakes the class its own fallback table.Drone.new(...)creates a fresh table, attachesDroneas its metatable, fills in its own fields and returns it.- Methods use the colon, so
selfis the object.
Every object gets its own health, and every object shares the one copy of damage that lives on Drone.
local Drone = {}
Drone.__index = Drone
function Drone.new(name, health)
local self = setmetatable({}, Drone)
self.name = name
self.health = health
return self
end
function Drone:damage(amount)
self.health = math.max(0, self.health - amount)
return self.health
end
local a = Drone.new("A", 100)
local b = Drone.new("B", 100)
print(a:damage(34), a:damage(34), b.health)
print(rawget(a, "damage"), a.damage == b.damage)
66 32 100
nil trueWith max health 100 and wrench damage 34, a drone made with Drone.new("A", 100) takes how many :damage(34) calls to reach 0?
Answer
3 calls. 66 after one hit, 32 after two, and math.max(0, -2) is 0 after three. Beacon Yard's real drone also falls on the third wrench hit.
Open this step in lesson mode · Link to this step · This confused me
5Other metamethods
__index is not the only metamethod. A few others are worth knowing:
__tostringdecides whatprintandtostringshow.__eqdecides what==means for two objects.__add,__muland friends let objects use arithmetic; Roblox's ownVector3behaves this way.__newindexruns when you write a key the table does not have, which is how read-only or validated tables are built.
local Drone = {}
Drone.__index = Drone
Drone.__tostring = function(self)
return `Drone {self.name} at {self.health} health`
end
function Drone.new(name)
return setmetatable({ name = name, health = 100 }, Drone)
end
print(Drone.new("A"))
Drone A at 100 healthOpen this step in lesson mode · Link to this step · This confused me
7Inheritance, briefly
A class can fall back to another class. Give Boss a metatable whose __index is Drone, and a boss object first looks in its own table, then in Boss, then in Drone. Boss can replace a method and still call the original. This is inheritance.
local Drone = {}
Drone.__index = Drone
function Drone.new(health)
return setmetatable({ health = health }, Drone)
end
function Drone:damage(amount)
self.health -= amount
return self.health
end
local Boss = setmetatable({}, { __index = Drone })
Boss.__index = Boss
function Boss.new()
return setmetatable(Drone.new(300), Boss)
end
function Boss:damage(amount)
return Drone.damage(self, amount / 2)
end
print(Boss.new():damage(34))
283Chains of three or four classes get hard to follow quickly: to know what boss:damage does, you must read every level. That is why most Roblox studios avoid deep inheritance.
boss:damage(34) is called on an object made by Boss.new. In what order does Luau look for damage?
Answer
1. The boss object's own table 2. The Boss class table 3. The Drone class table. The object has no damage field, so its metatable's __index sends Luau to Boss. Boss defines damage, so the search stops there; if it did not, Boss's own metatable would send Luau on to Drone.
Open this step in lesson mode · Link to this step · This confused me
8Composition: build from parts
Instead of a family tree of classes, build an object from smaller parts it owns: a health part, a mover, a stun timer. Each part does one job and can be reused by anything (a drone, a crawler, a turret). This is compositionCompositionBuilding an object from smaller parts it owns, instead of inheriting from a parent class.Think of it as assembling a robot from standard modules rather than breeding it from another robot., and the usual advice is to prefer it over inheritance.
local Health = {}
Health.__index = Health
function Health.new(max)
return setmetatable({ current = max, max = max }, Health)
end
function Health:take(amount)
self.current = math.max(0, self.current - amount)
return self.current == 0
end
local function newDrone()
return { health = Health.new(100), speed = 12 }
end
local function newTurret()
return { health = Health.new(250) }
end
local drone = newDrone()
local turret = newTurret()
drone.health:take(34)
print(drone.health.current, turret.health.current)
66 250A later milestone adds a ground crawler that walks and can be stunned, but cannot fly. With composition, what does the crawler get?
Answer
A Health part and a stun timer, plus its own walking mover. With composition you reuse the parts that fit and leave out the ones that do not. Inheriting from Drone would drag in flying and then fight it.
Open this step in lesson mode · Link to this step · This confused me
9When not to use classes in Roblox
Classes earn their keep when you have many things of the same kind with their own state: projectiles, enemies, inventory slots. Much of a Roblox game is not like that.
| In the picture | In Roblox |
|---|---|
| A department | A service such as Players, or a game service such as CoinService |
| The one front door | game:GetService(name), or require of the service module |
| Asking at the desk | Calling the service's functions |
- Services are singletons. There is one
CoinService, oneDataService. A module table with functions is already one object; a class with one instance only adds ceremony. - Data that is saved or sent must be plain. When a table is sent across the network between server and client (Module 3) or saved to persistent storage (Module 6), Roblox keeps only plain data and strips metatables2. Beacon Yard's
Profileis a plain table for that reason. - Roblox already has objects. A
Part, aModelor aToolwith attributes and tags is often the right object, and other systems can find it.
Both sidesRemember: Services is departments with one front door.
Beacon Yard needs three drones, each with its own health. Should DroneService itself be copied three times?
Answer
No. One DroneService can manage a separate state record or object for each drone.. The service is shared. Each drone needs its own state, not another copy of the service that manages it.
Where does it break?“Departments with one front door” is a good picture of services. Where does it stop being true?
It breaks here. There is exactly one of each department, fetched by name. When you need many of something, such as fifty drones, a department is the wrong shape and you want a class or plain records.
The true model. Engine services and Beacon Yard's own services are singletons: one per side, reached by name or require. Things that come in numbers are modelled as instances, records or class objects that a service manages.
Why is Beacon Yard's Profile ({ coins = 0 }) a plain table and not a class with methods like profile:spend(25)?
Answer
Saved and networked data only keeps plain values, so metatables and methods would not survive. Persistent storage and network messages carry plain data only, so a loaded profile would lose its metatable and methods. Keeping the functions on DataService and the data plain avoids that trap.
Open this step in lesson mode · Link to this step · This confused me
10Choosing a style
Ways to organise game objects in Luau
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Module table of functions | One table with functions, state in module locals. Beacon Yard's services. | Singletons: services, controllers, config. | Only one of it; awkward if you later need many. |
| Metatable class | Table, __index and a new constructor. | Many objects with their own state and shared behaviour: projectiles, enemies, UI widgets. | Colon and dot mix-ups; data loses its metatable if saved or sent across the network. |
| Closure objects | A function that returns a table of functions closing over private locals. | Small objects that need truly private state. | Each object carries its own copy of every function, so memory grows with the count. |
| ECS (jecs, Matter) | Entities are ids; components are plain data; systems loop over all entities with given components. | Games with thousands of similar things, or studios that want data-oriented code. | A different way of thinking; overkill for a small game. |
Go deeper Typing a class
Under --!strict, the usual way to name a class's type is export type Drone = typeof(setmetatable({} :: { health: number }, Drone)). The next lesson explains typeof in types and how the new type solver improves inference for patterns like this.
Match each Beacon Yard thing to the style that fits it best.
Answer
DataService: Module table of functions; Fifty wrench sparks with their own lifetimes: Metatable class; A player's saved Profile: Plain table of data; Thousands of identical crates with physics: ECS. One service: a module table. Many sparks with their own state: a class. Saved data: plain. Thousands of similar things: an ECS is built for that scale.
Open this step in lesson mode · Link to this step · This confused me
11Challenges
Level 1, Apprentice
Challenge
Give a class a readable printout.
- Start from
- Any Run cell in this lesson
Done means
- A Coin class has new(value) and a __tostring that prints Coin worth 5
- print(Coin.new(5)) shows that text
Hints
- Put __tostring on the class table, next to __index.
- Use string interpolation with self.value.
Solution
local Coin = {}
Coin.__index = Coin
Coin.__tostring = function(self)
return `Coin worth {self.value}`
end
function Coin.new(value)
return setmetatable({ value = value }, Coin)
end
print(Coin.new(5))
Level 2, Builder
Challenge
Build the Stun class in the cell below. Passing the tests completes this challenge.
- Start from
- The Run cell below
- Check it here
- Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.
Done means
- Stun.new(seconds) returns an object whose metatable is Stun
- start(now) and active(now) live on Stun, not copied onto each object
- Two Stun objects track independent timers and pass all assertions
Hints
- return setmetatable({ seconds = seconds, untilTime = nil }, Stun)
- active(now) returns self.untilTime ~= nil and now < self.untilTime.
Solution
local Stun = {}
Stun.__index = Stun
function Stun.new(seconds)
return setmetatable({ seconds = seconds, untilTime = nil }, Stun)
end
function Stun:start(now)
self.untilTime = now + self.seconds
end
function Stun:active(now)
return self.untilTime ~= nil and now < self.untilTime
end
-- Write a Stun class: Stun.new(seconds), stun:start(now) and stun:active(now).
-- active is true from start until start + seconds (exclusive).
-- Methods must live on Stun, not on each object.
local Stun = {}
Stun.__index = Stun
function Stun.new(seconds)
return {}
end
Level 3, Professional
Challenge
Start from the m14-ship tag in the game repo and write a reusable Cooldown class. You edit only challenges/oop_work.luau; the solution is challenges/solutions/oop.md in the game repo.
- Start from
- The game at milestone m14 (download)
- Grade it
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("oop")in the server command bar. Copy the pass code from Output.
Done means
- challenges/oop_work.luau defines Cooldown.new(gap), cooldown:ready(now) and cooldown:use(now)
- Methods live on Cooldown and are shared through the metatable
- use returns true and records the time only when ready; two cooldowns never share state
- The Course Runner prints TEST PASS for every oop check and a pass code
Hints
- Start new with local self = setmetatable({}, Cooldown).
- ready is true when nothing was recorded yet, or now - self.last >= self.gap.
- use calls ready first and only then writes self.last = now.
Open this step in lesson mode · Link to this step · This confused me
12Recap
Retiring the analogy
You no longer need “a shared recipe book”. __index is consulted only when a key is missing on read. Assignments create fields on the object itself. Mutable state, such as a hits table, must be created per object in the constructor.
Retiring the analogy
You no longer need “departments with one front door”. Engine services and Beacon Yard's own services are singletons: one per side, reached by name or require. Things that come in numbers are modelled as instances, records or class objects that a service manages.
Recap
- The colon passes the table as self: obj:method(x) is obj.method(obj, x). Mixing colon and dot puts the wrong value in self.
- A class is a table of methods with __index pointing at itself; new attaches it as the metatable of each object. Reads fall back to the class, writes stay on the object, so never keep shared mutable tables on the class.
- Prefer composition to inheritance, use module tables for singletons, and keep saved or networked data plain: metatables do not survive saving or network sends.
A class with __index is a shared recipe book, until only reads go to the book. Writes land on the card, and a table kept in the book is one shared table that every object changes.
Services is departments with one front door, until there is exactly one of each department, fetched by name. When you need many of something, such as fifty drones, a department is the wrong shape and you want a class or plain records.
Queued for review
- In drone.damage(34), which value lands in self?
- A Drone tracks each player's last hit time in a hits table. In a class version, where must that table be created?
- boss:damage(34) is called on an object made by Boss.new. In what order does Luau look for damage?
- Why is Beacon Yard's Profile ({ coins = 0 }) a plain table and not a class with methods like profile:spend(25)?
- Match each Beacon Yard thing to the style that fits it best.
Open this step in lesson mode · Link to this step · This confused me