When and how should I use ModuleScripts?

I’ve never really used ModuleScripts for anything other than using them to return text fields for GUIs. I would like to expand my usage for them.

When and how should I utilize them, especially with large game projects?

Modulescripts are used for reusing and organizing code. You can use it for breaking down just about every system whether that be datastores, tools, builsing etc anything. Break down your systems into groups and have a modulescript for each group and when your script needs a function itll require that modulescript which also requires any dependencies for its functions.

3 Likes

We use them all the time - most of our codebase is in them.
First rule from The Pragmatic Programmer is Don’t Repeat Yourself - don’t copy and paste code. Every time you copy and paste code you’ve got more places you have to remember to change every time you need to make a fix or an improvement.
So how to share code with Roblox? You can use linked source, but the debugger doesn’t work with that. You can use events and remotefunctions, but that’s a pretty big pain. We put our code in modules, and have very small scripts, often just a few lines, that require those modules and call the functions within. An analog to this practice is modules and #includes in C++.

10 Likes

Lua in ModuleScripts don’t run on game startup. Instead, ModuleScripts run when they are require()d by scripts and LocalScripts. ModuleScripts MUST return ONE value, generally being a table containing the functions and properties of the module. They provide nothing of a performance benefit, although, if you want to share the exact same code on the server and client, leaving the code in a ModuleScript in repStorage may be a good idea.

EDIT: ModuleScript documentation for anyone else wondering

10 Likes

Specifically, the first time they are required. All subsequent requires of the module (on the same machine) will just return the already-created table without executing the module’s code again.

7 Likes

You can modify the variables and what not in the modulescript environment and have it apply for all scripts using it which is great.

1 Like

For anyone curious, require(module:Clone()) is the common way around this, should you ever have to.

5 Likes