Preventing the loading of the same module the code is executing from


How would I go about checking the run context of the code, see if it’s a module script, check what module script it is and with that prevent the loading for the same module in the module loader section of the code in the picture

2 Likes

FYI, modules will only run once per server and per client. If you’re trying to prevent this module from running twice on the client, it shouldn’t as is unless you have other copies of said module.

If you’re trying to prevent the client from requiring a server module or vice versa, you can use RunService to check if the run context is client or server.

Problem it’s calling the same module that’s loading the module in some of the modules that are being required. So I want to limit this.

Ah, I see. Ideally you’d want to avoid having dependencies that can cause the module to require itself over and over.

I would move any functions in your MainModule that is used by other modules to another module, where you can then just require that or reference your global table.

Typically when I have these kinds of hierarchical setups, I have a Loader script that will assign all child modules to a shared table, and when there is a need for a module that is unloaded, I write while not shared[ModuleName] do task.wait() end in the module somewhere.

Just to clarify, MainModule is basically a global module that’s used across most scripts in the game to easily access services, modules and other stuff in replicated storage etc. So my problem is loading the modules with that global module for the use of other scripts when the modules themselves need the global module. Making another module responsible for loading modules wouldn’t fix my issue I’m pretty sure.

Also i noted an error in your module. Just wondering if you were looking into it. Server is not a valid member of game.

It’s G.Server
G.Server = G.RunService:IsServer()

Something you can do to get around cyclic dependencies, is having a method like :RegisterMainModule(MainModule) inside of every individual module you have. This would replace the require(MainModule) inside of your modules. But be careful with this approach, as circular dependencies are avoided for a reason, that is, it is possible that a module has not be required yet when another needs it. You can implement some yielding mechanic with coroutines, but then you have to make sure 2 modules aren’t waiting for each other to load, leading to an infinite yield (although that is easy to find and avoid)

For a yielding mechanic, you’d need a method inside your main module such as :GetModule(ModuleName). It isn’t possible to do so with simple indexes, even with metatables, as metatable functions aren’t allowed to yield

Yeah I’d rather sort this issue in my global module instead of going to every single script in the game and adjusting it to work with that