Open Asterune
Sharing code with modules

Sharing code with modules

Define ModuleScript exports and use require to share code.

A ModuleScript executes on first require and caches its first return value for the current execution group and Luau VM. Later calls in that context receive the cached value.

Define a module

A module can return a value for callers to use. This example exports a table containing a function. No return value, or a nil return, is cached as true. Create a ModuleScript named Scoring in ReplicatedStorage.

Luau
local Scoring = {}
function Scoring.pointsFor(kills, assists)
  return kills * 10 + assists * 4
end
return Scoring

Require a module

require accepts a ModuleScript instance.

Luau
local storage = game:GetService("ReplicatedStorage")
local Scoring = require(storage:WaitForChild("Scoring"))
print(Scoring.pointsFor(3, 2))

Execution and state

The server, clients, and execution groups have separate module caches. Scripts using the same group and Luau VM share a cached return value. Changes to returned tables do not replicate to other contexts.

Module placement

Use ReplicatedStorage for modules needed on both sides. Clients can read these modules, so they must not contain secrets.

Use ServerStorage or ServerScriptService for server-only modules. A caller must be able to access the module to require it.

Use script.Parent for module lookups relative to the executing script. This keeps local dependencies valid when their containing model is moved or cloned.

Circular dependencies

Circular require dependencies raise cyclic ModuleScript require. Move shared code into a third module or remove the cycle.