Question about using require() on ModuleScript's

Hi, So I have a Question about using require() on a ModuleScript.

So lets say I have a Script that is within StarterCharacterScripts that uses require() on a ModuleScript, if the Player were to die and Respawn with the same script, would they be able to continue using the Script as Normal? Or would that one time require() cause it to not work?

Plus, If the Player were to Die with the ModuleScript required, would that cause Issues since it was already required by the Script? or would It be garbage collected (or something like that?) since the Script was Destroyed and Therefore no longer exists?

Just a Question I have because I’m concerned about what would Happen if I did this.

5 Likes

Thats not exactly what I’m asking but thanks.

I’m asking what would happen if a Script is Destroyed while having required modules within?

Nothing. If the script’s RunContext is Legacy, it’ll likely stop executing.

As for the modules, nothing would happen either.

(I’m not sure if this helps but)

See, the way modules work (you may already know this but putting it out here for others) is that the first time the module is required, the contents are executed and the return value is stored for later.

The second time the module is required, the execution is skipped and the return value is given directly.

So, the actual module won’t be affected. Only things related to the return value.

(I’m not totally sure but I think if the return value is a table, it is cloned. DONT QUOTE ME ON THIS)

2 Likes

Like what @majdTRM said, due to how modules work, nothing will happen even if the script that required it was deleted. The script will stop running (because it’s deleted), and the module script stays intact for other scripts to use it.

You can test that with this:

--@ module script

local module = {}

function module.test()
	warn("hi im still intact")
end

return module
--@ local script

local module = require(game:GetService("ReplicatedStorage").ModuleScript)

module.test() --@ prints "hi im still intact"
2 Likes

Yes, but what will happen to the required part of the Script, will It cause a Memory Leak, or Slow down the game?

Or does it get garbage collected?

Idk, Im just concerned.

1 Like

As I mentioned, the required part isn’t garbage collected because it is persistent. All other scripts get the same return value.

If the ModuleScript is destroyed or no longer depended upon, it is garbage collected.

Requiring the script multiple times shouldn’t cuase a memory leak of any sorts.

2 Likes

Thanks thats all I wanted to know.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.