Tutorial · Scripting foundations

How to use ModuleScripts in Roblox Studio

Once a game has more than a few scripts, the same code starts to appear in several of them: the same prices, the same "format this number" function, the same coin-giving code. A ModuleScript fixes that. It is a script that does not run on its own; instead, other scripts load it with require and use what it gives back. This guide explains how that works, builds three useful modules step by step, and covers the mistakes behind the most common module errors.

Updated 14 November 20269 min readBeginnerLuauWritten by

In short

A ModuleScript holds code that other scripts load with require(moduleScript). It must end with return and one value, usually a table of settings or functions. The first require runs the module and remembers what it returned; every later require in the same place gets that same table. Put shared modules in ReplicatedStorage, and server-only modules in ServerScriptService.

  • A module runs once per side: the server has its own copy, and each player's device has its own. Changing a module's table on a client does not change it on the server.
  • Every Script that requires the same module on the server gets the same table, so a module can hold data that several scripts share.
  • Forgetting the return at the end gives the error "Module code did not return exactly one value".

Get the script

Server coin module shared by every script

A ModuleScript in ServerScriptService that keeps each player's coins and lets any server Script read, add and spend them with one set of rules.

ModuleScript in ServerScriptService named CoinService
-- ModuleScript in ServerScriptService named CoinService.
-- The one place that changes coins. Server Scripts call get, add and spend.
local Players = game:GetService("Players")

local STARTING_COINS = 50

local coins: { [Player]: number } = {}
local labels: { [Player]: IntValue } = {}

local CoinService = {}

function CoinService.get(player: Player): number
	return coins[player] or 0
end

function CoinService.add(player: Player, amount: number)
	if amount <= 0 or not coins[player] then
		return
	end
	coins[player] += amount
	labels[player].Value = coins[player]
end

-- Returns true and takes the coins if the player can afford it; otherwise changes nothing
function CoinService.spend(player: Player, amount: number): boolean
	local balance = coins[player]
	if not balance or amount <= 0 or balance < amount then
		return false
	end
	coins[player] = balance - amount
	labels[player].Value = coins[player]
	return true
end

-- This code runs once, the first time any Script requires CoinService
local function onPlayerAdded(player: Player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	local label = Instance.new("IntValue")
	label.Name = "Coins"
	label.Value = STARTING_COINS
	label.Parent = leaderstats
	leaderstats.Parent = player
	coins[player] = STARTING_COINS
	labels[player] = label
end
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	onPlayerAdded(player)
end
Players.PlayerRemoving:Connect(function(player: Player)
	coins[player] = nil
	labels[player] = nil
end)

return CoinService

RoCode builds it in the place you have open in Roblox Studio, on Windows or macOS with a desktop browser; on a phone the button sends the prompt and the link to your computer. Free to start, with free credits every day. More Roblox Studio scripts

Where to put it

Explorer: one module, used by any number of server Scripts
ServerScriptService
  CoinService ModuleScript new
  CoinPickups Script
  ShopHandler Script

Settings you can change

STARTING_COINSIn the script
Coins each player starts with when they join. Default: 50.

Require it from server Scripts only: require(ServerScriptService:WaitForChild("CoinService")). Clients cannot see ServerScriptService, which is the point: they cannot change coins.

Type-checked with luau-lsp strict against Roblox's API definitions on 14 November 2026. Not playtested in Studio yet: press Play and watch the Output window before you publish.

Prompt for RoCode

Add a CoinService ModuleScript in ServerScriptService that stores each player's coins in a table, shows them as a Coins leaderstat, starts everyone at 50, and has get, add and spend functions where spend refuses if the player cannot afford it, then use it from my coin pickup and shop scripts.

On this page
  1. Get the script
  2. What it is
  3. 1. Settings
  4. 2. Functions
  5. 3. Shared data
  6. Where they go
  7. Server vs client
  8. Mistakes
  9. 4. Test
  10. Common errors
  11. With RoCode
  12. Questions
  13. Sources

What a ModuleScript is

Roblox has three kinds of script. Two of them run by themselves; the third waits to be asked.

The three kinds of script
KindRunsUsed for
ScriptBy itself, on the serverGame rules: rounds, damage, saving, rewards.
LocalScriptBy itself, on one player's deviceInput, camera, GUI, effects.
ModuleScriptOnly when another script calls require on itCode and data that several scripts share.

A new ModuleScript starts like this:

ModuleScript in anywhere named NewModule
local module = {}

return module

The module makes a table, can put things in it, and returns it. Whatever comes after return is what require hands back. It can be a table, a function or a number, but it must be exactly one value, and most modules return a table.

If you are new to Script and LocalScript, read where scripts run first. This guide assumes you know that the server and each player's device run different code.

Step 1: A module of settings

The simplest useful module is a list of numbers you would otherwise copy into many scripts. When you want to change a price, you change it here once.

  1. In the Explorer, hover over ReplicatedStorage, click + and insert a ModuleScript. Name it GameConfig.
  2. Replace its contents with the code below.
ModuleScript in ReplicatedStorage named GameConfig
-- ModuleScript in ReplicatedStorage named GameConfig.
-- Numbers that both server Scripts and LocalScripts need. Change them here, once.
export type Config = {
	StartingCoins: number,
	RoundSeconds: number,
	SwordPrice: number,
	MaxPlayersPerTeam: number,
}

local GameConfig: Config = {
	StartingCoins = 50,
	RoundSeconds = 180,
	SwordPrice = 250,
	MaxPlayersPerTeam = 8,
}

return GameConfig

Now any script can read it. This Script in ServerScriptService and this LocalScript in StarterPlayerScripts both use the same sword price:

Script in ServerScriptService named ConfigTest
-- Script in ServerScriptService named ConfigTest.
local ReplicatedStorage = game:GetService("ReplicatedStorage")

type Config = {
	StartingCoins: number,
	RoundSeconds: number,
	SwordPrice: number,
	MaxPlayersPerTeam: number,
}
local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig")) :: Config

print("Server: a sword costs", GameConfig.SwordPrice)
LocalScript in StarterPlayerScripts named ConfigTestClient
-- LocalScript in StarterPlayerScripts named ConfigTestClient.
local ReplicatedStorage = game:GetService("ReplicatedStorage")

type Config = {
	StartingCoins: number,
	RoundSeconds: number,
	SwordPrice: number,
	MaxPlayersPerTeam: number,
}
local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig")) :: Config

print("Client: a sword costs", GameConfig.SwordPrice)

Press Play and both lines appear in the Output. WaitForChild waits until GameConfig exists, which matters on the client: when a player joins, their device may start running scripts before everything in ReplicatedStorage has arrived.

Step 2: A module of functions

Modules are best known for holding functions. This one turns big numbers into short text like 1.5K or 2.3M, which every leaderboard, shop and HUD in a simulator needs.

  1. Insert a ModuleScript into ReplicatedStorage named NumberFormat.
  2. Paste the code below.
ModuleScript in ReplicatedStorage named NumberFormat
-- ModuleScript in ReplicatedStorage named NumberFormat.
-- NumberFormat.short(1500) is "1.5K"; NumberFormat.commas(1500) is "1,500".
local NumberFormat = {}

local SUFFIXES = { "K", "M", "B", "T" }

function NumberFormat.short(value: number): string
	local sign = if value < 0 then "-" else ""
	local size = math.abs(value)
	if size < 1000 then
		return sign .. tostring(math.floor(size))
	end
	local index = 0
	while size >= 1000 and index < #SUFFIXES do
		size /= 1000
		index += 1
	end
	-- One decimal place, without a trailing ".0"
	local text = string.format("%.1f", math.floor(size * 10) / 10)
	text = string.gsub(text, "%.0$", "")
	return sign .. text .. SUFFIXES[index]
end

function NumberFormat.commas(value: number): string
	local text = tostring(math.floor(math.abs(value)))
	-- Add a comma before every group of three digits, counting from the right
	local result = string.reverse((string.gsub(string.reverse(text), "(%d%d%d)", "%1,")))
	result = string.gsub(result, "^,", "")
	return (if value < 0 then "-" else "") .. result
end

return NumberFormat

Functions inside a module are written function NumberFormat.short(...), with a dot, which puts the function into the table under the name short. Other scripts call it the same way:

LocalScript in StarterPlayerScripts named FormatTest
-- LocalScript in StarterPlayerScripts named FormatTest.
local ReplicatedStorage = game:GetService("ReplicatedStorage")

type NumberFormatModule = {
	short: (value: number) -> string,
	commas: (value: number) -> string,
}
local NumberFormat = require(ReplicatedStorage:WaitForChild("NumberFormat")) :: NumberFormatModule

print(NumberFormat.short(1500)) --> 1.5K
print(NumberFormat.short(2340000)) --> 2.3M
print(NumberFormat.commas(1234567)) --> 1,234,567

A module like this has no data of its own and touches nothing in the game, so it is safe to use from anywhere. If you ever find a bug in it, you fix it in one place and every script gets the fix.

Step 3: A server module that shares data

Here is the feature that makes modules powerful. On the server, every Script that requires the same module gets the same table. So a module can hold data, like each player's coins, and every script sees the same numbers.

  1. Insert a ModuleScript into ServerScriptService (not ReplicatedStorage) named CoinService.
  2. Paste the code below.
ModuleScript in ServerScriptService named CoinService
-- ModuleScript in ServerScriptService named CoinService.
-- The one place that changes coins. Server Scripts call get, add and spend.
local Players = game:GetService("Players")

local STARTING_COINS = 50

local coins: { [Player]: number } = {}
local labels: { [Player]: IntValue } = {}

local CoinService = {}

function CoinService.get(player: Player): number
	return coins[player] or 0
end

function CoinService.add(player: Player, amount: number)
	if amount <= 0 or not coins[player] then
		return
	end
	coins[player] += amount
	labels[player].Value = coins[player]
end

-- Returns true and takes the coins if the player can afford it; otherwise changes nothing
function CoinService.spend(player: Player, amount: number): boolean
	local balance = coins[player]
	if not balance or amount <= 0 or balance < amount then
		return false
	end
	coins[player] = balance - amount
	labels[player].Value = coins[player]
	return true
end

-- This code runs once, the first time any Script requires CoinService
local function onPlayerAdded(player: Player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	local label = Instance.new("IntValue")
	label.Name = "Coins"
	label.Value = STARTING_COINS
	label.Parent = leaderstats
	leaderstats.Parent = player
	coins[player] = STARTING_COINS
	labels[player] = label
end
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	onPlayerAdded(player)
end
Players.PlayerRemoving:Connect(function(player: Player)
	coins[player] = nil
	labels[player] = nil
end)

return CoinService

Now two completely separate Scripts can use it. One gives 10 coins when a player touches a part tagged Coin; the other could be a shop that spends them. They never talk to each other, but they work on the same coin totals, because both got the same CoinService table.

Script in ServerScriptService named CoinPickups
-- Script in ServerScriptService named CoinPickups.
local CollectionService = game:GetService("CollectionService")
local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")

type CoinServiceModule = {
	get: (player: Player) -> number,
	add: (player: Player, amount: number) -> (),
	spend: (player: Player, amount: number) -> boolean,
}
local CoinService = require(ServerScriptService:WaitForChild("CoinService")) :: CoinServiceModule

local COIN_VALUE = 10

local function setUpCoin(coin: Instance)
	if not coin:IsA("BasePart") then
		return
	end
	local taken = false
	coin.Touched:Connect(function(hit: BasePart)
		local character = hit.Parent
		local player = if character and character:IsA("Model") then Players:GetPlayerFromCharacter(character) else nil
		if player and not taken then
			taken = true
			CoinService.add(player, COIN_VALUE)
			coin:Destroy()
		end
	end)
end

for _, coin in CollectionService:GetTagged("Coin") do
	setUpCoin(coin)
end
CollectionService:GetInstanceAddedSignal("Coin"):Connect(setUpCoin)

Because CoinService lives in ServerScriptService, players' devices cannot see it or require it. Only server code can change coins, and it can only change them through add and spend, which check the amounts. That is the same rule every guide on this site follows: the server decides anything that matters. For coins that survive leaving the game, the DataStore tutorial adds saving.

Where to put a ModuleScript

Where a module lives decides who can require it.

Module locations
Put it inServer Scripts can require itLocalScripts can require itUse for
ReplicatedStorageYesYesShared settings, item lists, helpers like NumberFormat.
ServerScriptServiceYesNo, it is never sent to devicesGame rules and data: CoinService, round logic, admin lists.
ServerStorageYesNo, it is never sent to devicesThe same as ServerScriptService. Many games keep modules here and Scripts in ServerScriptService.
StarterPlayerScriptsNoYes, from the player's own scriptsClient-only code: camera, input, GUI helpers.

One copy per side, not one copy per game

This trips up almost everyone once. A module in ReplicatedStorage is required separately on the server and on each device, and each one runs the module's code and gets its own table.

  • Server Script A and server Script B share one copy.
  • Your LocalScripts share another copy, on your device.
  • Another player's LocalScripts share a third copy, on their device.

So if a LocalScript does GameConfig.SwordPrice = 1, only that player's device sees a price of 1. The server still uses 250 when it takes the coins. That is good for safety, and it means a module is not a way to send data between the server and players. For that, use RemoteEvents or attributes.

Common ModuleScript mistakes

What goes wrong, and the fix
MistakeWhat you seeFix
No return at the end, or return with nothing after itModule code did not return exactly one valueEnd the module with return module.
An error anywhere in the module's codeRequested module experienced an error while loadingThe real error is printed above it in the Output. Fix that line.
Module A requires B and B requires ARequested module was required recursivelyMove the shared part into a third module that both require.
Passing a name instead of the ModuleScriptAttempted to call require with invalid argumentsPass the object: require(ReplicatedStorage:WaitForChild("GameConfig")).
A LocalScript requiring a module in ServerScriptServiceInfinite yield possible, because the client never receives itMove shared modules to ReplicatedStorage.
Calling Module:fn() when it was written Module.fnThe first argument is the module table instead of what you passedUse the same symbol: a dot for functions written with a dot.

One more: a module's top-level code should finish quickly. If it waits (for example a task.wait(10) outside any function), every script that requires it waits too, because require does not return until the module returns.

Step 4: Test it

  1. Press Play with the scripts from Steps 1 and 2. The Output shows the sword price from both the server and the client, then 1.5K, 2.3M and 1,234,567.
  2. For Step 3, tag a few parts Coin (Properties window, Tags, +). Touch them: your Coins in the player list go up by 10 each.
  3. To prove the scripts share one table, add a second Script that prints CoinService.get(player) every few seconds. It shows the coins the pickup script gave.
  4. Delete the two test scripts (ConfigTest and ConfigTestClient) and FormatTest when you are done.

Common errors and fixes

Module errors usually name the module and a line. These are the ones beginners meet most.

Module code did not return exactly one value

The module has no return at the end, or returns two values. End it with exactly one, such as return CoinService. See the full fix.

attempt to call a nil value when using a module function

The function name is misspelt, or it was never put in the returned table (written local function short instead of function NumberFormat.short). See attempt to call a nil value.

My change to the module does nothing in the game

The module runs once, on the first require. Changes to its table on a client stay on that device. Stop and start Play after editing a module.

Two scripts show different coin totals

One of them is a LocalScript, which has its own copy of every module. Coins should be read on the client from the leaderstats or an attribute the server sets.

Build it with RoCode

If you would rather not set this up by hand, RoCode can build it in the place you have open. RoCode is an independent AI agent for Roblox Studio, not made by Roblox: you describe the change in a web chat, and its Studio plugin creates the parts and scripts in your Explorer, so there is no code to paste.

You type

Move the prices and the coin-giving code that are copied across my scripts into ModuleScripts: shared settings in ReplicatedStorage and a CoinService in ServerScriptService, then update the scripts to require them.

RoCode does
  • Can read your scripts first to find the code that is repeated, then moves it into modules
  • Writes the scripts with Create Script and is told to compile-check each one with Check Script
  • Sets an undo point before and after each batch of changes, so Ctrl+Z steps back one batch at a time

How RoCode connects to Studio.

Questions

What is a ModuleScript in Roblox?

A script that does not run by itself. Other scripts load it with require, and it gives back one value, usually a table of settings or functions, so the same code can be used in many scripts.

How do I use require in Roblox?

Pass the ModuleScript object: local GameConfig = require(ReplicatedStorage:WaitForChild("GameConfig")). The variable then holds whatever the module returned.

Where should I put ModuleScripts?

In ReplicatedStorage if both the server and clients need it, in ServerScriptService or ServerStorage if only the server should, and in StarterPlayerScripts for client-only code.

Does a ModuleScript run every time it is required?

No. It runs once per side, the first time it is required, and later requires on that side get the same returned value.

Can ModuleScripts share data between the server and the client?

No. The server and each device have their own copy. Use RemoteEvents or attributes to send data between them.

What is the difference between a Script and a ModuleScript?

A Script runs by itself on the server. A ModuleScript only runs when required, and returns something for the script that required it to use.

Sources and further reading

How the code was checked: every script on this page passes Luau's strict type checker against Roblox's API definitions (luau-lsp, 14 November 2026). A type check catches misspelt APIs and wrong types, not game logic, so playtest in Studio before you publish.

Try RoCode on your own place.

Free every day, no card required. Install the plugin, describe the feature, and review what lands in Studio.