So, I looked on the DevHub for what a ModuleScript is, and I didn’t understand a thing. I hope someone can give me a simple explanation on:
- What a ModuleScript is in simple terms
- How to use it and why it would be useful
Help would be appreciated.
So, I looked on the DevHub for what a ModuleScript is, and I didn’t understand a thing. I hope someone can give me a simple explanation on:
Help would be appreciated.
A ModuleScript is, well, that, a module as a script. I often use it to write general functions in that I think Roblox should have by default, I can then import these functions in other scripts using the built-in require
function.
A variable, it can be a table, a number, a true/false, it all depends on what it “returns”.
First, you need to make one. You can simply create a ModuleScript using the little plus icon that appears when you hover over something in the explorer. In it, you will find the following default code:
local module = {}
return module
You use ModuleScripts by require
ing them, for example a ModuleScript in the workspace would be used by doing:
local Module = require(workspace.ModuleScript)
Basically, whatever is return
d by the modulescript is what require
will return. In the case of the default code, the modulescript makes an empty table called “module”, and return
s it. So,
local Module = require(workspace.ModuleScript)
local Table = {}
Module
and Table
in the above example mean the same thing, aka, an empty table, assuming the ModuleScript has the default code.
If you change the ModuleScript code to
return 1000
, then doing
print(require(workspace.ModuleScript))
will print 1000
, because the ModuleScript returns 1000.
It allows you to Modul
arize (apologies for the pun) code. Modularized code is easy to maintain, as the boundaries of a ModuleScript is clearly defined. A “WeaponModule” just handles weapons, eg equipping them, playing their animations. If you put all your code into 1 script, it’d be hard to read and disorganized.
Edit: As @dudesa3000 has said, it also makes it easier to edit specific parts of your game without breaking others. Instead of hopelessly searching through a 5000 line script that handles everything, you can simply change some code in a 50 line ModuleScript.
--In ModuleScript
local Module = {}
function Module.Add(A, B)
return A + B
end
function Module.Square(X)
return X * X
end
return Module
--In script
local MathModule = require(...)
print(MathModule.Square(2))
print(MathModule.Add(9, 10))
A ModuleScript is like a reference book. You can use it over and over again. Doesn’t that remind you of a function?
Well, it’s like a function, except it’s a whole script that stores the function so you can use it from any script.
It also helps for editing. If you run into something you want to change you can just change the one line instead of going individually through each script that could have used a module script