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.
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
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.