Module Scripts: Reusable Code Architecture
Organize your codebase with ModuleScripts—require patterns, singletons, and shared utilities.
Introduction
ModuleScripts are Roblox's mechanism for code reuse. Instead of copying the same function into ten scripts, write it once in a ModuleScript and require it wherever needed. This hub teaches module patterns that keep projects organized as they grow from one script to hundreds.
The Require Pattern
local MyModule = require(game.ReplicatedStorage.Modules.MyModule). ModuleScripts return a table (or function) as their last expression. return { doSomething = function() end }. The require cache means each module loads once per environment.
Project Organization
Group modules by domain: Combat/, UI/, Data/. Use init.lua pattern for folder-based modules. Keep configuration in separate Config modules. Avoid circular requires—if A requires B and B requires A, refactor shared code into C.
Use Cases
- Shared utility libraries
- Configuration management
- Service singletons
Best Practices
- Return tables, not bare functions, for extensibility
- Document module APIs with comments
- Keep modules focused on one responsibility
Troubleshooting
Script runs but nothing happens in-game
Verify the script type matches its location. Server Scripts belong in ServerScriptService; LocalScripts in StarterPlayerScripts or StarterGui. Check the Output window in Studio for error messages.
Changes don't appear after editing
Stop and restart Play mode in Studio. Some scripts cache values on first run. For published games, republish after testing locally.