ModuleScripts!
ModuleScripts is a Lua source container, that is only ran once, and can only return one value.
local module = {}
return module
How do we use these? I have a couple of examples:
local myFunc = function() print("I am a function from a ModuleScript.") end;
return myFunc
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).
local repstore = game:GetService("ReplicatedStorage")
local myReturnedFunc = require(repstore:WaitForChild("myModuleScript"))
myReturnedFunc()
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:
local myTable = {
myFunc = function()
print("I am a function inside a table.")
end;
myFuncTwo = function()
print("I am the second function inside the same table.")
end;
}
return myTable
or,
local myTable = {}
function myTable.myFunc()
print("I am a function inside a table.")
end;
function myTable.myFuncTwo()
print("I am the second function inside the same table.")
end;
return myTable
How you call these functions are similar to the last way, except you need to get the functions from the returned table.
local repstore = game:GetService("ReplicatedStorage")
local myReturnedTable = require(repstore:WaitForChild("myModuleScript"))
myReturnedTable.myFunc()
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
1 comment
Have you tried module scripts?