Global Variables, Global Scope?

As we all know, Global Variables go under _G. I am wondering when it is appropriate to use _G. given that you can define a global variable without using it?
Example:

x = 4;
print(x)

Is it still accessible across scripts without _G? What are the rules of do’s and don’t’s? I was playing with them and realized you can’t set global variables (for the purpose of using them across scripts) without _G. when you want to use them across scripts, so I’m still left sort of confused.

2 Likes

No, _G is for variables that can be used script-wide those variables can be used anywhere in the script they’re defined in.

2 Likes

No, _G is a global variable accessible across multiple scripts, whereas smth like this

x = 4;
print(x)

is only accessible in the script it was created

3 Likes

In your example, the variable is not accessible by other scripts, while variables in _G are. However, ModuleScripts should always be used over _G.

3 Likes

This makes a lot more sense, thanks all.

1 Like

Mostly don’t use it because unmanaged global state is a sin. Usually try to have a single source of truth for all state. But yes you can use it in certain occasions such as accessing a framework module to avoid repeated calls for requiring it (I have seen loleris do it). An awful use case is using _G to store player data. Also keep in mind that client and server environments have different _G i.e setting smth to _G in server won’t replicate to client side scripts

Ping cuz post has been edited @Th1rust

1 Like

Is it bad to replace a module script with functions defined with _G so you don’t need to require?

Depends on the context, but generally yes, unless it a reference to a framework module or a custom loader (even then people don’t use _G), it’s considered a bad practice. Also, if you are worried about the tedious repeated calls to require the module, you can just use a custom loader that loads in the modules, attach it to _G and then get that reference from other scripts. Another approach would be to have a module/framework which bootstraps your game and holds reference to the folders of your utiltity modules and then attach this module to _G. I do something like that with Knit.

local Knit = _G.Knit

local Janitor = require(Knit.Util.Janitor)
local Promise = require(Knit.Util.Promise)

Here Util points to the Packages folder in ReplicatedStorage where I usually store my external dependencies. The drawback with this approach is that you lose out on intellisense and typing and I myself am trying to migrate away from this approach and adopt a simple modular architecture without frameworks.

1 Like

Thanks a ton, this helped a lot with managing my code.

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