Should I put a piece of code into a function or into the global scope?

I’m writing a module script right now, and I have some of the code outside of a function run(), in the global scope, and most of the code inside it. The run function is then called by the main (and the only) regular script, it activates a game mechanic.

Now I see no reason to keep this stuff in the global scope, but I’m unsure if I should move it into the run() function, it’s just some variable initialization, and a for loop inserting stuff into a table.

Also, if I require a service, should it be in the global scope or inside the function, or does it depend?

the code inside a modulescript will be executed each time it is require()'ed

The code inside your function will be be executed each time the function is executed.

If the module is required by multiple scripts, the code outside functions will run multiple time.
If you want the code in module to be executed only once, put it inside your run() function

2 Likes

Oh man, that’s really making it much easier, thank you.

1 Like

ModuleScripts only run once upon their first time being require()'d as per documentation. You can easily test this by creating a simple ModuleScript with a single print like so then requiring it from two separate scripts:

local module = {}

print("you should only see this once")

return module

As ModuleScripts only execute the code within themselves once, only one print will be executed and appear when running the game. Note that a :Clone() of a ModuleScript counts as a new distinct module and will execute the code within itself when you require() it for the first time as well.

If the initialization code you’re considering moving to your run() function is vital for the module functioning (i.e. it MUST run before the module can be properly used) then you should consider leaving it outside so you’re 100% sure it’s been executed before any script tries to use the module after require()-ing it.

Services from game:GetService() should be perfectly fine to leave in the “global scope” (I assume you mean local upvalues at the very top of the module?) since they’re essentially constants. Other “services” like ChatService are a bit more finnicky since they might not exist right away, so you could justify making a function to get/cache those.

1 Like