You should check out AlvinBlox’s tutorial instead here!
Jump to:
Tutorial
ModuleScripts
are an excellent way to enforce the DRY principle of not repeating yourself.
ModuleScripts
are often used for storing functions that you need to use across multiple scripts. Now, rather than creating the same function again and again and again across a multitude of scripts, it’d be much more prudent just to use ModuleScripts
. In this tutorial, I’ll be covering how to use these scripts.
local module = {} -- notice how this is what a table looks like?
return module
This is what a ModuleScript looks like when you create one in Studio.
Let’s create a basic function.
local module = {} -- notice how this is what a table looks like?
function module.print(text) -- you can include parameters like you can in a normal function.
print(text) -- prints text to console
end
return module
If you run this code, nothing will happen because it’s a function and it needs to be called before it will do anything.
ModuleScripts are brilliant for following the DRY principle because you can call them from different scripts using require()
.
Let’s have a look.
Create a new script and parent it to the same thing as the ModuleScript.
local Module = require(script.Parent:WaitForChild("ModuleScript")) -- insert this code into your script.
Running it like this won’t do anything.
So let’s call the function this time:
local Module = require(script.Parent:WaitForChild("ModuleScript")) -- insert this code into your script.
Module.print("Hello!")
If you run that code, in Output in Studio or the Developer Console > Server, you should be able to see “Hello!”.
Before I noted that the first line in a ModuleScript is like a table - this is because ModuleScripts are essentially function holders that can be accessed by other scripts.
This means that you should be able to run a for
loop over the ModuleScript, returning the name of the function as the index, and the function itself as the value.
So there you go, now you have yourself a basic ModuleScript function:
-- MODULESCRIPT CODE --
local module = {} -- notice how this is what a table looks like?
function module.print(text) -- you can include parameters like you can in a normal function.
print(text) -- prints text to console
end
return module
-- SCRIPT/LOCALSCRIPT CODE --
local Module = require(script.Parent:WaitForChild("ModuleScript")) -- insert this code into your script.
Module.print("Hello!")
You may also want to look at this article for more information on ModuleScripts:
ModuleScript
Edit:
It’s worth noting that ModuleScripts can return any one value, not just tables, but tables (if not functions) are typically the most useful thing to reuse.