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.
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
Step 1 of 10
One 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
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
Press 1 to 4 to choose, Enter to check.
Step 2 of 10
A 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.
| In the picture | In Roblox |
|---|---|
| The first person writing the board | The first require running the module's body |
| Everyone reading the same board | Later requires returning the same table |
| Writing on the board | Changing a field of the returned table, seen by every holder |
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.
Step 3 of 10
The shape of a Beacon Yard module
Every module in the game has the same shape:
local CoinService = {}makes the table that will be returned.- Locals inside the file (
local function playerFromHit,local function spawnCoin) are private: other scripts cannot reach them. - Functions on the table (
function CoinService.start(pads)) are public. return CoinServiceat 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
A server script runs local CoinService = require(script.CoinService). Which of these can it call or read directly on CoinService?
Press 1 to 4 to choose, Enter to check.
Step 4 of 10
Where 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.

Select a numbered pin, or a row below, to read what it marks.
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?
Press 1 to 4 to choose, Enter to check.
Step 5 of 10
Requiring 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())
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()?
Press 1 to 4 to choose, Enter to check.
Step 6 of 10
State 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.
Step 7 of 10
Where 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.
The server command bar requires Config twice and compares the results.
Transcript
- 0:00 Server command bar. This bar has its own require cache, separate from the running server script.
- 0:01 Requiring Config twice in this bar returns the same table, so the compare prints true.
- 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?
Press 1 to 4 to choose, Enter to check.
Step 8 of 10
Build 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
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Explicit requires and start calls | One 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. |
| Knit | A 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 loader | A 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 script | A 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
src/shared/Config.luau
Run
git checkout m03-coins-countand keeprojo serverunning.You should see Studio syncs the m03 files: ReplicatedStorage.Shared holds Config, and the Server script has CoinService and DataService as children.
In
src/shared/Config.luau, addprint("config ran")on the line abovereturn 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.
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.
Stop. Remove the print with
git checkout -- src/shared/Config.luau.You should see git status shows a clean working tree.
Step 9 of 10
Challenges
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
Meet the criteria above, then record your own result. No test grades this check.
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
Meet the criteria above, then record your own result. No test grades this check.
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?
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 rungame.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
Step 10 of 10
Recap
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
- 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.
- The server, each client and Studio's command bar each have their own cache, and cyclic requires raise 'Requested module was required recursively'.
- 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.
Queued for review
- 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?
- 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?
- 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?
- CoinService and another server module both require DataService. CoinService adds 5 coins to a player's profile. What does the other server module see?
- Why does init.server.luau separate require(script.DataService) from DataService.start()?