_G or module script

*As I was learning about global variables, there was a post saying that global variables aren’t too good for utilizing and you should instead use module scripts. I want to know the pros and cons of each thing.

I know global variables should be used more for small not really impactful stuff like making it so the time of day pauses/continues etc

I heard somewhere that module scripts are good for communicating from script to script and I also know how to use them decently well (just basically a script that can be used for multiple scripts by requiring it)

Thanks

ModuleScripts are better because _G although it can be used on server and client, any variables from _G that’s in a server script can’t be passed to the client. ModuleScripts are faster than _G and isn’t recommended by Roblox. overusing _G causes lag overall they are just better.

2 Likes

I would like to point out that _G works on the client too. But values set in _G do not cross the server-client barrier.

4 Likes

No, it can be used in any script, but if you add something to _G in a server script then it won’t be there in a localscript.

It isn’t.

The reason it isn’t recommended is because it’s global. Any code can change the value anywhere, which makes it very difficult to debug. It can also cause race conditions, i.e.;

--Script 1

_G.MyVeryImportantValue = 5

--Script 2

if _G.MyVeryImportantValue == 5 then
    print("Hello world!")
else
    while true do end
end

MyVeryImportantValue might not exist when Script 2 is running, causing Script 2 to freeze the game. This is a mistake I’ve seen a lot with _G. Of course, the fix is simple, just add a task.wait to the top of Script 2, but that can get very cluttered fast, and is generally seen as a “band-aid” by most. This doesn’t happen with modules, as require yields until the module returns, which is why they are recommended over _G.

cc @ChickHenEn

6 Likes

After further testing I can confirm this is the case, my bad.

localscript:
Screenshot 2022-06-27 230303

localscript results:
Screenshot 2022-06-27 230214
serverscript:
Screenshot 2022-06-27 230249

1 Like

Thanks! I’m pretty sure I know how to do this, but could you give me an example that makes it so if a variable is true something runs?