What does the _G property actually do?

Hello!

So I was recently reading some toolbox scripts and practicing my coding skills by cleaning them up and making them more efficient when I came across a few lines I wasn’t sure I understood. They used the _G property, which when I looked it up on the documentation, it said it’s a table that is shared between all scripts of the same context level. So I guess if my scripts have the RunContext property set to the same Enum as other scripts, I can share information and data.

I’m not sure if I understood this correctly, so could someone please let me know if I’m not? Also, could I please have a better explanation or a maybe code sample? If so, thank you and have a wonderful day! :slight_smile:

Don’t use it, prefer to use ModuleScripts.

_G will share code between scripts of the same context. For example, if you create a LocalScript and store a table in _G.MainSettings like this:

_G.MainSettings = {MAX_STUDS = 10}

Therefore, you will have access to _G.MainSettings.MAX_STUDS in all existing LocalScripts on the client.

You can also edit the value of _G.MainSettings.MAX_STUDS on every LocalScript.

Remember that if you use _G in multiple LocalScripts, use a yield to wait for the LocalScript containing the assignment of your _G to be executed.

repeat task.wait() until (type(_G.MainSettings) == "table") -- Yield

local MainSettings = _G.MainSettings
print(MainSettings.MAX_STUDS) -- 10

MainSettings.MAX_STUDS += 10

print(_G.MainSettings.MAX_STUDS) -- 20

You can use _G on the server and the client but they do not replicate from one to the other which is why we say that the information is only shared in scripts of same RunContext.

I want to reiterate that _G is not a good solution; prefer to use ModuleScripts.

1 Like

Basically _G means _Global as it allows any variable set as:

_G.MyVariable = "Hello World!!"

to be used in mulitple scripts so you can call _G from different scripts.

See this post for more info.

1 Like

Thank you both for responding! I now know how this is used! Have a wonderful day! :slight_smile:

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