Is the Lua global function _G can be trusted?

These days, I’ve seen a lot of scripting posts where its scripting code has this Lua global function _G, which creates a global variable that can be used in a thread.

However, is it still trustable? Or is it been deprecated forever? I’m confused by this now because I’ve seen some people saying this function is not recommended to be used.

_G works different in vanilla Lua than on Roblox. On the former, _G points to the global environment.

a = 5

is the same as

_G.a = 5

and

a

is the same as

_G.a

You implicitly add it to _G.

This works too:

_G.a = 5
print(a)

For security reasons, on Roblox, _G does not point to the global environment. It’s not deprecated, but it is not seen as a good practice. Doing something like this in one script

_G.a = 5

will allow you to read _G.a in another script.

print(_G.a) -- 5 (or maybe nil)

Notice the (or maybe nil), since it is possible that the script that reads it runs before the one that writes to _G.a, therefore needing to do something like

repeat wait() until _G.a ~= nil

which is bad for obvious reasons.

And then there is name collisions, it will be a bit difficult to find what script may have accidentally modified a certain variable. Modules are better for this instead. Modules won’t have the issue of needing to poll, and it makes dependencies static and explicit.

4 Likes

So do you think that nowadays developers uses this? If so, what are some examples?

In all honesty, I feel like _G is becoming less and less relevant due to ModuleScripts taking the lead. I’m not surprised either considering that ModuleScripts are more superior and you have more control on what to do with them.

I wouldn’t choke up if Roblox was in the process of deprecating _G, I could see it potentially happening.

I see, thanks for helping me out.