Lesson 2 of 6

ModuleScripts and require

Learn how Roblox ModuleScripts and require work, including the require cache, per-side copies and cyclic require errors, by reading how Beacon Yard's server boots its services.

Concept lesson, about 70 minutes, 10 steps

By the end you can

  • Write a ModuleScript that returns a table, and require it from a script
  • Predict when a module's body runs, and why a second require returns the same table
  • Follow Beacon Yard's require(script.X) layout and its split between the require list and the start list

Before this: Luau basics, part 2: Luau tables, holes, sets and copying

1One file for every number

At m03-coins-count, Beacon Yard gains a file called Config.luau. It holds two numbers, the coin value and the respawn time, and ends with return Config. Nothing in it runs on its own. CoinService gets the numbers with one line: local Config = require(Shared:WaitForChild("Config")).

local Config = {
	COIN_VALUE = 5,
	COIN_RESPAWN_SECONDS = 4,
}
 
return Config
Figure 1.1

You add print("config ran") just above return Config. Three server modules each require Config during one Play. How many times does the line print on the server?

-- Config.luau
local Config = { COIN_VALUE = 5 }
print("config ran")
return Config
  1. Once
  2. Three times
  3. Never; modules do not print
  4. Once per player who joins
Answer

Once. The first require on the server runs the body and stores the returned table. The other two get the stored table, so the print appears once.

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

2A module returns one value

A ModuleScriptModuleScriptA script that returns a value, usually a table of functions, for other scripts to require.Think of it as one shared whiteboard per side. is a script that returns exactly one value, usually a table of functions and settings. It does nothing until some other script calls require(moduleScript). The first require on a side (server or client) runs the body and caches the returned value. Every later require of the same ModuleScript on that side returns that same value, without running the body again1.

Both sidesModuleScript and require is one shared whiteboard.
In the pictureIn Roblox
The first person writing the boardThe first require running the module's body
Everyone reading the same boardLater requires returning the same table
Writing on the boardChanging a field of the returned table, seen by every holder

See the whole analogy cast

A module is a whiteboard in a shared office. The first person in writes it up. Everyone after reads the same board, and if someone writes on it, everybody sees the change.

Think of it as One shared whiteboard

The cell below builds a tiny require with a cache table, so you can watch the rule happen. Roblox's real require does the same job for ModuleScripts.

Luau
local cache = {}
local runs = 0
local function configModule()
	runs += 1
	return { COIN_VALUE = 5 }
end
local function require(module)
	if cache[module] == nil then
		cache[module] = module()
	end
	return cache[module]
end
local a = require(configModule)
local b = require(configModule)
print(runs, a == b)
b.COIN_VALUE = 8
print(a.COIN_VALUE)
Figure 2.1. Expected output: 1 true 8

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

3The shape of a Beacon Yard module

Every module in the game has the same shape:

  1. local CoinService = {} makes the table that will be returned.
  2. Locals inside the file (local function playerFromHit, local function spawnCoin) are private: other scripts cannot reach them.
  3. Functions on the table (function CoinService.start(pads)) are public.
  4. return CoinService at the end hands the table to whoever requires it.

CoinService at m03-coins-count shows all four parts cleanly:

local CoinService = {}
 
local function playerFromHit(hit: BasePart): Player?
	local character = hit:FindFirstAncestorOfClass("Model")
	if not character then
		return nil
	end
	return Players:GetPlayerFromCharacter(character)
end
 
local function spawnCoin(pad: BasePart)
	local coin = Instance.new("Part")
	coin.Name = "Coin"
	coin.Shape = Enum.PartType.Ball
	coin.Anchored = true
	coin.CanCollide = false
	coin.CanTouch = true
	coin.Size = Vector3.new(1.6, 1.6, 1.6)
	coin.Color = Color3.fromRGB(255, 204, 64)
	coin.Material = Enum.Material.Neon
	coin.CFrame = pad.CFrame + Vector3.new(0, 2.2, 0)
	coin:SetAttribute("CoinValue", Config.COIN_VALUE)
	coin.Parent = pad
	CollectionService:AddTag(coin, "Coin")
 
	local claimed = false
	local seen: { [Player]: boolean } = {}
 
	coin.Touched:Connect(function(hit: BasePart)
		if claimed then
			return
		end
		local player = playerFromHit(hit)
		if not player then
			return
		end
		if seen[player] then
			return
		end
		seen[player] = true
		claimed = true
 
		local value = coin:GetAttribute("CoinValue")
		local amount = if typeof(value) == "number" then value else Config.COIN_VALUE
		DataService.addCoins(player, amount)
		coin:Destroy()
 
		-- Tests shorten the wait with this workspace attribute. The game
		-- never sets it, so Play uses the Config number.
		local delaySeconds = Config.COIN_RESPAWN_SECONDS
		local override = workspace:GetAttribute("TestCoinRespawnSeconds")
		if typeof(override) == "number" and override >= 0 then
			delaySeconds = override
		end
		task.delay(delaySeconds, function()
			if pad.Parent then
				spawnCoin(pad)
			end
		end)
	end)
end
 
function CoinService.start(pads: { BasePart })
	for _, pad in pads do
		spawnCoin(pad)
	end
end
 
return CoinService
Figure 3.1

A server script runs local CoinService = require(script.CoinService). Which of these can it call or read directly on CoinService?

  1. CoinService.start(pads)
  2. CoinService.playerFromHit(part)
  3. CoinService.spawnCoin(pad)
  4. type(CoinService)
Answer

CoinService.start(pads); type(CoinService). start is a field on the returned CoinService table (and type(CoinService) is "table"). playerFromHit and spawnCoin are local functions inside the file, so they stay private.

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

4Where modules live, and how to reach them

Rojo maps Beacon Yard's folders into Studio. src/server becomes one Script named Server in ServerScriptService, and every other file in that folder becomes a child ModuleScript of it. So the boot script reaches its services with require(script.CoinService): script is the Server script, and the modules are its children. Sibling modules reach each other with script.Parent.X, the way CoinService requires script.Parent.DataService.

Shared modules such as Config live in src/shared, which becomes ReplicatedStorage.Shared. Both the server and each client can see ReplicatedStorage, so both can require Config. A script that might run before the folder arrives uses WaitForChild.

Roblox Studio
Roblox Studio's Explorer during Play: ServerScriptService contains a Script named Server, and the service modules are listed as its children.

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

Figure 4.1.

The service modules are children of the Server script, not of ServerScriptService.

This is the top of src/server/init.server.luau at m03. The server fails at boot with DataService is not a valid member of ServerScriptService. Which line is wrong?

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataService = require(script.Parent.DataService)
local CoinService = require(script.CoinService)
DataService.start()
Answer

Line 2: local DataService = require(script.Parent.DataService). Fixed: local DataService = require(script.DataService). script.Parent is ServerScriptService, which does not contain the modules. They are children of the Server script, so the path is script.DataService.

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

5Requiring is not starting

Requiring a Beacon Yard service only defines its functions. Nothing connects or spawns until the boot script calls start. Look at m03-coins-count's init.server.luau: it requires both services first, then calls DataService.start() before CoinService.start(coinPads()):

local DataService = require(script.DataService)
local CoinService = require(script.CoinService)
 
local function coinPads(): { BasePart }
	local folder = workspace:WaitForChild("Yard"):WaitForChild("CoinPads")
	local pads: { BasePart } = {}
	for _, child in folder:GetChildren() do
		if child:IsA("BasePart") then
			table.insert(pads, child)
		end
	end
	return pads
end
 
DataService.start()
CoinService.start(coinPads())
Figure 5.1

Why keep them apart? A module body runs at the moment of its first require, in whatever order requires happen. start calls run in the exact order you write. By m06-drone-wrench, the server has fourteen requires at the top and a separate, deliberate start list below them. Module 3's boot-order lesson walks that whole sequence.

Why does init.server.luau separate require(script.DataService) from DataService.start()?

  1. So requiring only loads definitions, and the boot script controls the exact order services start in
  2. Because ModuleScripts are not allowed to run code until start() is called by Roblox
  3. Because require cannot run more than one line
  4. So each require makes a fresh copy of the module
Answer

So requiring only loads definitions, and the boot script controls the exact order services start in. A module body runs on first require, which can depend on which file happened to require it first. Separating start() puts the boot order in one visible list.

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

6State in a module, and starting twice

Because a module's table is shared by everyone who requires it on that side, module-level variables are shared too. DataService keeps every player's profile in one profiles table at the top of its file, and every server module that requires DataService sees the same profiles. That is the point of a service.

It also means calling start twice would connect everything twice. Services guard against that with a started flag so start can safely be called more than once. Programmers call that idempotent.

Luau
local CoinTracker = {}
local started = false
local connections = 0
function CoinTracker.start()
	if started then
		return
	end
	started = true
	connections += 1
end
CoinTracker.start()
CoinTracker.start()
print(connections)
Figure 6.1. Expected output: 1

CoinService and another server module both require DataService. CoinService adds 5 coins to a player's profile. What does the other server module see?

  1. The new balance, because both hold the same DataService table and its profiles
  2. The old balance, because each require makes a fresh copy
  3. Nothing until the player rejoins
  4. An error, because two scripts cannot require one module
Answer

The new balance, because both hold the same DataService table and its profiles. One. The first require ran DataService's body; every other server require got the same table, so they share the profiles table inside it.

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

7Where the whiteboard picture breaks

Both sidesRemember: ModuleScript and require is one shared whiteboard.

Studio's command bar can require modules too. Watch what it gets.

Figure 7.1.

The server command bar requires Config twice and compares the results.

Transcript
  1. 0:00 Server command bar. This bar has its own require cache, separate from the running server script.
  2. 0:01 Requiring Config twice in this bar returns the same table, so the compare prints true.
  3. 0:04 COIN_VALUE on that table is 5.
Where does it break?“One shared whiteboard” is a good picture of modulescript and require. Where does it stop being true?

It breaks here. There is one board per side, not one per game: the server, each client and Studio's command bar each run the module once and hold separate tables.

The true model. require caches a ModuleScript's return value per Luau environment. The server, every client and the command bar are separate environments, so state in a module is shared only within one of them. Cross-side data must travel by replication or remotes.

Because the server, each client, and Studio's command bar each have their own require cache, requiring a service from the command bar creates a fresh, empty copy instead of reaching the live server's state; that is why Beacon Yard runs its test suite through RunGameTests, as explained in Playtesting: Play, Run, Team Test, server and client views: Beacon Yard's own tests.

Both the server and a player's client require ReplicatedStorage.Shared.Config. The client sets Config.COIN_VALUE = 999 on its copy. What does the server's Config.COIN_VALUE read?

  1. 5, because the server and each client have separate require caches
  2. 999, because both required the same ModuleScript
  3. nil, because writing to a required module clears it
  4. An error, because clients cannot require modules in ReplicatedStorage
Answer

5, because the server and each client have separate require caches. require caches per Luau environment. The server and every client each run Config once and hold their own table, so a client editing its copy never affects the server.

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

8Build it: watch the cache work

How should a game load its modules? Beacon Yard uses the plainest answer on purpose.

Ways to load and start modules

OptionWhat it isWhen pros pick itTrade-offs
Explicit requires and start callsOne entry script requires each module and calls start in a written order. Beacon Yard does this.Small and mid-size games, teaching code, teams who want boot order visible in one file.The list grows by hand; nothing stops a module from being required and never started.
KnitA framework of services and controllers with KnitInit and KnitStart hooks.Existing games built in its heyday; you will meet it when you join an older codebase.Archived: its README says it is no longer maintained. It also hides boot order behind its own lifecycle and networking layer.
Nevermore loaderA large set of packages with a service bag that resolves dependencies.Big codebases that want dependency injection and many shared packages.Much to learn; packages come through npm.
Auto-loader scriptA loop that requires every ModuleScript in a folder and calls start on each.Teams that want zero boot boilerplate.Start order becomes folder order, which is how subtle boot bugs appear.

Build along

m03-coins-count

  • src/shared/Config.luau
  1. Run git checkout m03-coins-count and keep rojo serve running.

    You should see Studio syncs the m03 files: ReplicatedStorage.Shared holds Config, and the Server script has CoinService and DataService as children.

  2. In src/shared/Config.luau, add print("config ran") on the line above return Config. Save. Press Play.

    You should see After Play, Output shows config ran exactly once, on the server. At this tag the client does not require Config, so there is no client line.

  3. During Play, switch the command bar to the server and run local a = require(game.ReplicatedStorage.Shared.Config) local b = require(game.ReplicatedStorage.Shared.Config) print(a == b).

    You should see Output prints true.

  4. Stop. Remove the print with git checkout -- src/shared/Config.luau.

    You should see git status shows a clean working tree.

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

9Challenges

Level 1, Apprentice

Challenge

A file only runs when something requires it. On m06-drone-wrench, find the server module that the boot script does not require directly, and explain why it still runs.

Start from
The game at milestone m06 (download)

Done means

  • You name one file in src/server that init.server.luau never requires
  • You find which module requires it instead, so you know whether its body runs

Hints

  1. Compare the file list in src/server with the fourteen require lines.
  2. Search the folder for the word Analytics. CoinService spells the require one way, and the other services spell it another way.
Solution
luau
-- Analytics.luau is not in init.server.luau's require list.
-- CoinService requires it with script.Parent.Analytics, and ShopService,
-- RoundService and others reach it through a childModule helper.
-- Either way its body still runs, once, the first time one of them is required.

Level 2, Builder

Challenge

Write a module whose state is private but shared by everyone who requires it.

Start from
Any Run cell in this lesson

Done means

  • A Counter module table has increment() and get() functions
  • Its count lives in a private local, not on the returned table
  • Two requires through the fake require above share one count

Hints

  1. Start from the fake-require cell and write a counterModule function that builds and returns the table.
  2. Keep local count = 0 inside counterModule, above the functions that use it.
Solution
luau
local function counterModule()
	local count = 0
	local Counter = {}
	function Counter.increment()
		count += 1
	end
	function Counter.get()
		return count
	end
	return Counter
end

In m06-drone-wrench, Remotes.luau defines a private list REMOTE_NAMES with five event names (RoundState, Feedback, ShopOpen, ShopBuy, Swing). What does #REMOTE_NAMES evaluate to?

Answer

5. REMOTE_NAMES has five entries, so #REMOTE_NAMES is 5. The level 3 challenge publishes that count as an attribute from the live module.

Level 3, Professional

Challenge

Switch to m06-drone-wrench (where Remotes.luau and challenges/luau-modules.luau live) and publish the count from the live Remotes module. The written solution is challenges/solutions/luau-modules.md in the game repo.

Start from
The game at milestone m06 (download)
Grade it
To grade work from an earlier milestone, apply your challenge changes to a checkout based on m14-ship, which includes the Course Runner. In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("luau-modules") in the server command bar. Copy the pass code from Output.

Done means

  • At the end of Remotes.init, the Remotes folder gets an attribute RemoteCount equal to #REMOTE_NAMES
  • Self-check, the test cannot see it: the number comes from the list, not a typed 5
  • The Course Runner prints TEST PASS luau_modules_remote_count and a pass code

Hints

  1. folder:SetAttribute("RemoteCount", #REMOTE_NAMES) writes a value any script can read.
  2. Put it after the loop, so a second init still refreshes it.
  3. The test reads the attribute from the folder instance, so it works even from another require cache.

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

10Recap

Retiring the analogy

You no longer need “one shared whiteboard”. require caches a ModuleScript's return value per Luau environment. The server, every client and the command bar are separate environments, so state in a module is shared only within one of them. Cross-side data must travel by replication or remotes.

Recap

  1. A ModuleScript returns one value. The first require on a side runs its body and caches the value; later requires on that side get the same table.
  2. The server, each client and Studio's command bar each have their own cache, and cyclic requires raise 'Requested module was required recursively'.
  3. Beacon Yard requires child modules with require(script.X), shares Config in ReplicatedStorage, and keeps start calls in a separate written order.

ModuleScript and require is one shared whiteboard, until there is one board per side, not one per game: the server, each client and Studio's command bar each run the module once and hold separate tables.

Next Events, signals and the task library

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