Answered by
6 years ago Edited 6 years ago
Module Scripts
Module Scripts are scripts that can store anything. This can be given to both the client and server. _G lacks on this ability.
NOTE: When I say array, it is technically the same thing as a table
Let's start by setting up our first ModuleScript code
Let's insert our first module script in ReplicatedStorage
This table is being returned at the end of our module script. I will explain later on why our return is very useful.
Let's put our first function inside of here
03 | function module.announce() |
04 | print ( "This function is in a module" ) |
NOTE: Values in ModuleScripts must be global(after looking at incapaz's anwser)
Just like arrays, you can insert values.
How to use ModuleScripts
Now that we have set up our ModuleScript, how can we use this?
We have a built-in function called require(). This returns what we have returned in our ModuleScript(remember our module array)
1 | local moduleScript = require(game.ReplicatedStorage.ModuleScript) |
You can use moduleScript.announce()
in a LocalScript as well(You could not do this if you were to use _G)
Private Modules
A cool thing about ModuleScripts is that you can take an ID of a ModuleScript and require it.
Let's take an example!
1 | local privateModule = require( 0431449 ) |
2 | privateModule.PrintFunc() |
A huge downside to this is that you can't test it in studio. Especially when you have to test a game that heavily relies on Private Modules. Another downside that can be countered is that an exploiter can require the private module, then, parent it to a Data Model, save the game and then steal your private module. To easily counter this, place script = nil
on the top of the ModuleScript.
I am hoping this helped you understand ModuleScripts and why you should use it over _G