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.

Concept lesson, about 75 minutes, 12 steps

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:

luau
local current = {
	health = 100,
	maxHealth = 100,
	stunnedUntil = 0,
	hits = {},
}
Roblox Studio
Beacon Yard during a drill: the drone with a health bar above it chases the player across the yard.

Select a numbered pin, or a row below, to read what it marks.

Figure 1.1.

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?

  1. One
  2. One per player
  3. Six, one per pad
  4. As many as the round spawns
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.

Luau
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)
Figure 2.1. Expected output: 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)
  1. 34
  2. drone
  3. nil
  4. amount
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.

Both sidesA class with __index is a shared recipe book.
In the pictureIn Roblox
The recipe bookThe class table that holds the methods
Each cardAn object made by new, holding its own fields
The note: see the book for anything not on this cardThe metatable's __index pointing at the class

See the whole analogy cast

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

Luau
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)
Figure 3.1. Expected output: Drone1 100 12 nil 66 100

Open 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:

  1. local Drone = {} holds the methods.
  2. Drone.__index = Drone makes the class its own fallback table.
  3. Drone.new(...) creates a fresh table, attaches Drone as its metatable, fills in its own fields and returns it.
  4. Methods use the colon, so self is the object.

Every object gets its own health, and every object shares the one copy of damage that lives on Drone.

Luau
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)
Figure 4.1. Expected output: 66 32 100 nil true

With 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:

  • __tostring decides what print and tostring show.
  • __eq decides what == means for two objects.
  • __add, __mul and friends let objects use arithmetic; Roblox's own Vector3 behaves this way.
  • __newindex runs when you write a key the table does not have, which is how read-only or validated tables are built.
Luau
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"))
Figure 5.1. Expected output: Drone A at 100 health

Open this step in lesson mode · Link to this step · This confused me

6Where the recipe book breaks

Both sidesRemember: A class with __index is a shared recipe book.

Reading through __index works like the book. Writing does not: self.health = 66 writes onto the object's own card, never into the book. The trap is a table that lives in the book. Every object reads the same one, and a change made through any object changes it for all.

Luau
local Drone = { hits = {} }
Drone.__index = Drone
function Drone.new()
	return setmetatable({}, Drone)
end
function Drone:recordHit(player)
	self.hits[player] = true
end
local a = Drone.new()
local b = Drone.new()
a:recordHit("Ava")
print(b.hits.Ava)
Figure 6.1. Expected output: true
Where does it break?“A shared recipe book” is a good picture of a class with __index. Where does it stop being true?

It breaks here. 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.

The true model. __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.

A Drone tracks each player's last hit time in a hits table. In a class version, where must that table be created?

  1. Inside Drone.new, as self.hits = {}, so every drone gets its own
  2. On the Drone class table, so all drones can share it
  3. In Config, so both sides can read it
  4. In __index
Answer

Inside Drone.new, as self.hits = {}, so every drone gets its own. A table on the class is one table for every object. Creating it in new gives each drone its own, just as spawnCoin creates a fresh seen set for each coin.

Open 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.

Luau
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))
Figure 7.1. Expected output: 283

Chains 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?

  1. The Boss class table
  2. The Drone class table
  3. The boss object's own table
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.

Luau
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)
Figure 8.1. Expected output: 66 250

A later milestone adds a ground crawler that walks and can be stunned, but cannot fly. With composition, what does the crawler get?

  1. A Health part and a stun timer, plus its own walking mover
  2. It must inherit from Drone and switch off flying
  3. A copy of DroneService
  4. Nothing: enemies cannot share code
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.

Both sidesServices is departments with one front door.
In the pictureIn Roblox
A departmentA service such as Players, or a game service such as CoinService
The one front doorgame:GetService(name), or require of the service module
Asking at the deskCalling the service's functions

See the whole analogy cast

  • Services are singletons. There is one CoinService, one DataService. 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 Profile is a plain table for that reason.
  • Roblox already has objects. A Part, a Model or a Tool with 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?

  1. No. One DroneService can manage a separate state record or object for each drone.
  2. Yes. Each drone needs a separate service fetched by name.
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)?

  1. Saved and networked data only keeps plain values, so metatables and methods would not survive
  2. Metatables do not work on the server
  3. Classes cannot hold numbers
  4. Plain tables are always faster to read
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

OptionWhat it isWhen pros pick itTrade-offs
Module table of functionsOne 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 classTable, __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 objectsA 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.

  1. DataService
  2. Fifty wrench sparks with their own lifetimes
  3. A player's saved Profile
  4. Thousands of identical crates with physics
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

  1. Put __tostring on the class table, next to __index.
  2. Use string interpolation with self.value.
Solution
luau
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

  1. return setmetatable({ seconds = seconds, untilTime = nil }, Stun)
  2. active(now) returns self.untilTime ~= nil and now < self.untilTime.
Solution
luau
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
Luau
-- 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
Figure 11.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. Start new with local self = setmetatable({}, Cooldown).
  2. ready is true when nothing was recorded yet, or now - self.last >= self.gap.
  3. 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

  1. 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.
  2. 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.
  3. 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.

Next Types: strict mode, the new type solver, generics

Open this step in lesson mode · Link to this step · This confused me