I was wondering, could module scripts hold more than one module? I am currently learning to use module scripts so I might not understand some of the stuff you say, so please try to keep it simple and clear.
Yes. Module scripts can contain multiple modules. Why not?
Then how would I extract them? from what I know, you have to use require(the location of the script.the name of the script).
What do you mean by “extract”?
from what I know the purpose of module scripts are to take out modules (tables with values and strings) and use them in other scripts. Am I wrong?
Store whatever the other modules return inside a parent module’s table.
Maybe something like:
local parentModule = {}
local module1 = require(path.to.module1)
local module2 = require(path.to.module2)
parentModule.m1 = module1
parentModule.m2 = module2
return parentModule
Then you can do things like
parentModule.m1
to access the stuff in module1
from parentModule
.
what is path and what is to?
It’s pseudocode for wherever the ModuleScript is.
Like workspace.Module
or wherever.
Yes, ModuleScripts can hold more than themselves, they’re valid because of the nice parent-child instance hierarchy that Roblox works with.
If you’re looking to access these ModuleScripts, then ideally you would be creating a dictionary in order to access them and returning that dictionary so that any other script requiring the module receives the table and can access your modules via their indice.
For example, imagine you have a hierarchy like this:
<ReplicatedStorage> ReplicatedStorage
<ModuleScript> InputDevices
<ModuleScript> Keyboard
<ModuleScript> Gamepad
Your InputDevices ModuleScript would essentially act as a layer for accessing the other ModuleScripts. To do that, the dictionary that InputDevices returns will contain the contents of the children ModuleScripts (preferably the return values from the requires so you don’t avoid requiring many times unnecessarily). So for example:
-- Create a table and assign it to the variable InputDevices
local InputDevices = {}
-- Iterate through the children of the current script: happens only once and
-- that's when this ModuleScript gets first required.
for _, childModule in ipairs(script:GetChildren()) do
-- Set an index in the table InputDevices to the current iteration value's
-- name, and the value of this index to the returned value from require.
InputDevices[childModule.Name] = require(childModule)
end
-- Return our first table so any script calling require on InputDevices gets
-- a table back.
return InputDevices
Then, when you have another script and let’s say you wanted to access the Keyboard module. Now that it’s in the table, we can require our interface layer (InputDevices) and access the Keyboard index.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local InputDevices = require(ReplicatedStorage:WaitForChild("InputDevices"))
local Keyboard = InputDevices.Keyboard