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

Step 1 of 12

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

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.

Choose one

DroneService keeps the drone in one module-level variable, current. How many drones can exist at once?

DroneService keeps the drone in one module-level variable, current. How many drones can exist at once?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 12

Methods 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
Ctrl Enter runs the cell. Checked against the expected output
Predict the output

In drone.damage(34), which value lands in self?

function drone:damage(amount)
    self.health -= amount
end
drone.damage(34)
In drone.damage(34), which value lands in self?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 3 of 12

Metatables: 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
Ctrl Enter runs the cell. Checked against the expected output

Link to this step · This confused me

Step 4 of 12

A 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
Ctrl Enter runs the cell. Checked against the expected output
Work it out

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?

calls

Link to this step · This confused me

Step 5 of 12

Other 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
Ctrl Enter runs the cell. Checked against the expected output

Link to this step · This confused me

Step 6 of 12

Where 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
Ctrl Enter runs the cell. Checked against the expected output
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.

Choose one

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

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

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 7 of 12

Inheritance, 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
Ctrl Enter runs the cell. Checked against the expected output

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.

Put in order

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

Link to this step · This confused me

Step 8 of 12

Composition: 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
Ctrl Enter runs the cell. Checked against the expected output
Choose one

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

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

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 12

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

Choose one

Beacon Yard needs three drones, each with its own health. Should DroneService itself be copied three times?

Beacon Yard needs three drones, each with its own health. Should DroneService itself be copied three times?

Press 1 to 2 to choose, Enter to check.

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.

Choose one

Why is Beacon Yard's Profile ({ coins = 0 }) a plain table and not a class with methods like profile:spend(25)?

Why is Beacon Yard's Profile ({ coins = 0 }) a plain table and not a class with methods like profile:spend(25)?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 10 of 12

Choosing 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 the pairs

Match each Beacon Yard thing to the style that fits it best.

Link to this step · This confused me

Step 11 of 12

Challenges

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

Meet the criteria above, then record your own result. No test grades this check.

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; 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
Luau
Ctrl Enter runs the cell. Checked by 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

The Course Runner prints this code when the test passes.

Link to this step · This confused me

Step 12 of 12

Recap

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

Link to this step · This confused me