ModuleScripts!
ModuleScripts is a Lua source container, that is only ran once, and can only return one value.
How do we use these? I have a couple of examples:
3 | local myFunc = function () print ( "I am a function from a ModuleScript." ) end ; |
The above code will return myFunc
, which is a function that will print "I am a function from a ModuleScript." when it's called, defined as a variable.
Now, to run this function from a Script (Same with LocalScripts).
03 | local repstore = game:GetService( "ReplicatedStorage" ) |
04 | local myReturnedFunc = require(repstore:WaitForChild( "myModuleScript" )) |
To get the returned value from a ModuleScript, we use require
. For more information about this, you can take a look at this link: https://www.robloxdev.com/articles/Built-in-Functions-and-Variables/Roblox
myReturnedFunc is the returned function which was contained in the ModuleScript (myModuleScript).
And to call the function of course, we do myReturnedFunc()
.
The best thing about this, is that you can call this function from any Script/LocalScript aslong as the function is contained in a ModuleScript, and it is returned.
What if you want to use multiple functions in various scripts?
We use a table, and contain all the functions you want to call in it.
There are two ways to put a function in a table:
06 | print ( "I am a function inside a table." ) |
10 | print ( "I am the second function inside the same table." ) |
or,
05 | function myTable.myFunc() |
06 | print ( "I am a function inside a table." ) |
09 | function myTable.myFuncTwo() |
10 | print ( "I am the second function inside the same table." ) |
How you call these functions are similar to the last way, except you need to get the functions from the returned table.
03 | local repstore = game:GetService( "ReplicatedStorage" ) |
04 | local myReturnedTable = require(repstore:WaitForChild( "myModuleScript" )) |
06 | myReturnedTable.myFunc() |
07 | myReturnedTable.myFuncTwo() |
I hope I helped in any way, thanks for reading.
If you want to take a look at the wiki about this, here's the link:
https://www.robloxdev.com/api-reference/class/ModuleScript