Hi, I have a two local scripts that both use the same module script, and I have an .Init() method inside the module which adds required folders and variables. One script that calls the .Init() method, but If the other script loads before I get errors.
I just want to know how to structure modules and script executions/order to work well together/best practices for my issue. Should I have a main (local) script that just executes everything in a custom order? Should I make a module loader? (If so how would I stop scripts from requiring modules until after everything’s all setup)
I’m glad that more and more developers are getting into frameworks and module-based structures, and there are plenty of ways to resolve this type of problem. One of the ones I use and recommend for avoiding race conditions is to have 1 local script and 1 server script initialize a folder of modules.
So you would essentially convert your local scripts that require a module, into modules. Create a new local script that initializes those, and then they should be able to execute in order. It’s kind of hard to explain, but here’s an example:
Assuming that your localscripts are converted to modules and in a folder in ReplicatedStorage:
local directory = ReplicatedStorage.Modules
local modules = {}
local function initialize()
for _, moduleScript in directory:GetChildren() do
local module = require(moduleScript)
if not module.initialized then
module.initialized = true
task.spawn(module.init)
modules[moduleScript.Name] = module
end
end
end
And of course, if you require a module that’s not initialized yet, you can create a priority function that sorts given priority for each module.
-- Priority is default to 10 for lowest / undefined priority
table.sort(modules, function(a, b)
return a.priority or 10 < b.priority or 10
end
Another way is to require every script in a loop, then calling the init function in a loop afterwards.
So from what I’m getting here is to make a local (or server) module loader, and have all the modules that would be loaded be basically there own oop scripts?
Local module loads all the independent modules (that don’t need any other modules to initialize) in priority 1, then loads priority 2 which could reference those modules in priority 1. Is that what you meant? (Just for clarification)