Module Script
Overview
A ModuleScript is used to structure and separate common functionalities for reuse. It helps reduce code duplication and makes maintenance more efficient.
Recommended Execution Locations
For modules used by both server and client: It is common to place them in ReplicatedStorage (e.g., referencing a VectorUtil module in both Script and LocalScript).
For modules used only by the server: For security and management purposes, it is recommended to place them in ServerScriptService (e.g., referencing a ServerGameConstValue module in a Script).
For modules used only by the client: Depending on the use case, it is recommended to place them in StarterPlayerScripts or StarterCharacterScripts (e.g., referencing a GUI module in a LocalScript).
How It Works
Modules are executed when they are called explicitly (require). The results are cached upon the first call, and subsequent calls return the same value, which enhances execution efficiency and ensures consistency.
A module must return exactly one value. Calling
requireon a module that returns no value, returns more than one value, or has empty code raises an error.If a module yields during execution (e.g.,
task.wait()) and then fails with an error, anyrequirewaiting on that module also resumes by throwing an error. This error can be handled withpcall.
1. Implementing a Module Script
local UtilityModule = {}
function UtilityModule.PrintMessage(message)
print("PrintMessage : " .. message)
end
return UtilityModule2. Referencing & Using a Module Script
Module Script Applications
Utility Class
In ModuleScript
In Script or LocalScript
Data Class
In ModuleScript
In Script or LocalScript
Class Inheritance
In ModuleScript
In Script or LocalScript
Last updated