ModuleScripts
If you have 10 scripts that all need to calculate a player's level, you shouldn't copy and paste the math 10 times. Enter ModuleScripts.
What is a ModuleScript?
A ModuleScript is a script that does not run automatically. Instead, it holds a table of functions and data that other scripts can "require" and use. This prevents duplicate code and keeps your project clean.
Creating a Module
When you create a new ModuleScript, Roblox automatically generates a basic table setup. We simply attach functions to that table.
local MathHelper = {}
-- Attach a function to the module
function MathHelper.CalculateLevel(xp: number)
return math.floor(xp / 100) + 1
end
-- You must ALWAYS return the table at the end!
return MathHelper
Requiring a Module
To use the module inside a standard Script or LocalScript, you use the built-in require() function.
-- Load the module into memory
local MathHelper = require(game.ReplicatedStorage.MathHelper)
-- Use its functions!
local playerXP = 450
local currentLevel = MathHelper.CalculateLevel(playerXP)
print("Player is level: " .. currentLevel) -- Prints 5
Shared State
ModuleScripts also remember data. If Script A requires a module and changes a variable inside it, and then Script B requires the module, Script B will see the updated variable. This makes them perfect for storing game configuration data or active match states!