_G Global Variables Inquiry

_G is used to assign global variables that can be accessed through server/client scripts depending on which type of script it was initialized in.

I’ve read a countless number of forum posts inquiring about its use, and many of its responses allude to it being bad practice. I understand module scripts exist for a reason, and that there are times that module scripts are better to use rather than global variables for organization, practical and technical reasons.

I’ve found a use for global variables that seems pretty useful, and want to start incorporating it in a lot of my games since it helps condense my code. However, I want to know whether or not it’s truly “okay” to use _G in this sense, and if there are other ways one could utilize _G to their advantages.

-- Sample of what I could use _G for
_G.ReplicatedStorage = game:GetService("ReplicatedStorage")
_G.Utility = require(_G.ReplicatedStorage.Modules.Utility)

local part = _G.Utility.New("Part", workspace)
2 Likes

_G is a table into which you can assign keys and values as any other table.
_G can be useful for storing things like player money.

1 Like

_G is isolated from scripts and localscripts.
Meaning you can’t use _G variables you set on the server in client scripts.

script
_G.Foo = "Bar"

localscript
print(_G.Foo) -- returns nil

But I fail to understand how your example of _G usage is beneficial to you.
Wouldn’t this be easier:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Utility = require(ReplicatedStorage.Modules.Utility)

local part = Utility.New("Part", workspace)

Unless local part = Utility.New("Part", workspace) is actually present in another script, I don’t see the benefit, seems like a hassle.

1 Like

Right, I understand that by setting a global variable on the server, the client doesn’t have access to it and vice versa.

The reason why I indexed services and modules as global variables is so that my other scripts/modules can use it without defining the service again at the beginning of the script, you know what I mean?