So I made a function that I need for my game & it is supposed to be called when I push a button on the screen GUI but since the code for the GUI is on a local script I don't know how to make it call a function from another script.
BTW I have made the function into a global function but if necessary I can turn it back into a regular function.
ModuleScripts!
ModuleScripts is a Lua source container, that is only ran once, and can only return one value.
-- ModuleScript local module = {} return module
How do we use these? I have a couple of examples:
-- ModuleScript local myFunc = function() print("I am a function from a ModuleScript.") end; return myFunc -- The ModuleScript is placed in ReplicatedStorage, and it is named 'myModuleScript'.
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).
-- Script local repstore = game:GetService("ReplicatedStorage") local myReturnedFunc = require(repstore:WaitForChild("myModuleScript")) myReturnedFunc() --[[ Expected Output I am a function from a ModuleScript. ]]
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:
-- ModuleScript 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,
-- ModuleScript 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.
-- Script local repstore = game:GetService("ReplicatedStorage") local myReturnedTable = require(repstore:WaitForChild("myModuleScript")) -- This returns the table we made in the ModuleScript (myTable). myReturnedTable.myFunc() myReturnedTable.myFuncTwo() --[[ Expected Output I am a function inside a table. I am the second function inside the same table. ]]
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