I have a simple library ModuleScript that loads all the modules.
local Library = {}
local modules = game.ReplicatedStorage.Modules
local function Browse(module)
print(module)
if module.ClassName == "ModuleScript" then
Library[module.Name] = require(module)
end
end
for _, module in ipairs(modules:GetChildren()) do
print(modules:GetChildren())
Browse(module)
end
return Library
Scripts can require the Library module to access all the modules. However a problem arises when a module needs to interact with another module via the Library which results in a recursive loop
Any ideas for solutions?
Solution #1
- Doesn’t wait for the ModuleScripts to load
- Doesn’t need to be updated for every module added or removed
- Returns whatever the module indexed returns when required
- Doesn’t auto-fill at first
local Meta = {
__index = function(self, Key)
local Module = script:FindFirstChild(Key)
if not Module then return end
return require(Module)
end
}
return setmetatable({}, Meta)
---- Usage
Library["FooModule"]
Solution #2
- Modules will always be loaded when requiring the library
- Must update for every module added or removed
- Must require the modules you index
- Auto-fills
return {
FooModule = script:WaitForChild("FooModule"),
BarModule = script:WaitForChild("BarModule"),
...
}
--- Usage
require(Library["FooModule"])
I hope this helps
1 Like