Is it better to have a module script that holds variables or create them in every script you need them in?

Kinda went off in the title but I feel like doing it the module script method is more efficient and it also saves time and when you need to change a variable you just need to change it in one place, this is what im talking about basically

So in essence in every script I need to one of these variables I just require this module below and I have access to all the ones I need rather than having too re-write them over and over ex. player

2 Likes

It really depends on what those variables are for. For variables like those in the image above, it is far better to create these variables where they are needed instead of storing them in a ModuleScript.

I also would advise against naming variables for services like TweenService or UserInputService using initialisms (like you do when assigning keys to Vars), it makes the code harder to read.


Another thing to keep in mind is that the return value of a ModuleScript is not replicated from server to client.

Imagine we have this module…

return { randomNumber = math.random(1, 100) }

The server could require it and maybe get a value of 42, but if any client were to also require it (if it were placed in ReplicatedStorage for instance), they’d be very likely to get a different number.

Keep these in mind.

1 Like

It’s not better or worse. Well, it’s a bit worse because you might accidentally write a script to modify it which you don’t want.

But in terms of productivity not having to rewrite variables EVERY SINGLE TIME you need them in a different scripts does save time does it not?

@Sepruko Dont worry Id never pass a math.random function in a module

It’s typically best practice on Roblox to use game:GetService to get services per script (and at the top of the script), as it better conveys what services are being used in the script.

I didn’t say that you would, I was just giving an example of how ModuleScript return values are not replicated, as they are otherwise the same on every subsequent require on the same machine (and session).

dont worry I seperate server modules from client modules

Also could you explain why it’s best practice to do this?

Pretty curious as to why that is

An example is if a script requires UserInputService, it’s more than likely listening to user input and that fact is immediately obvious.

Yeah but I meant something other than that…

Then what did you mean? I’m confused.

When you are programming and creating new scripts do you initalize the same variables that you’ve intialized before in other scripts?

As I already said, it’s depends on what those variables are used for, and then went on specify that in your example (using services) should be done per script.

For constants, utility functions and whatnot that are used across your experience, yes they are most likely better kept in a ModuleScript.

1 Like

That’s exactly what I wanted to hear thank you.

1 Like