Doubts about the global variable "_G"

My doubt is that I don’t understand _G logic.

When I use that, it is a global table that can be called by any script. (So far I know)

I would like to know how I can add values or more tables inside _G.

Do I have to use table.insert or put the values directly?
And how can I store _G in a database, like Datastore2 or ProfileServicie?

Another doubt that came to me writing this, if _G is a global table, how would I do to save the tables of each player? do I have to create a subtable inside _G or can I save it directly?

1 Like

They are just like regular tables all the operations you can do on a normal table you can do on a Global table

2 Likes

_G Stands for global variable.
Its a variable that works across scripts.

Example:
image
In this script I am setting ok as a global variable and ok value to yes
image

Now i have other script named changing
image
Now i want to get that ok variable in this script and print it.
So i will do
image

Output:
image

2 Likes

Global variables are effectively the same as a module script, accessible from any script, imagine the _G as require.

If you want to use one as @dexanddeb said, it is the same as using a variable, but instead you are using _G at the start.

_G.GlobalValue = 1200
_G.Table1 = {}
_G.Table2 = {}
print(_G.Table1)

This would work from any script; just like a Module, only you wouldn’t need to right require()

1 Like

Then to save it in a database I do it as if it were a normal table, right?

While learning about _G is good, I would highly recommend avoiding using it in your code. Use ModuleScripts instead. It will save you headaches in the future. The main fault is that any script can modify _G, and there’s no guarantee that what you want inside of _G has been set yet.

4 Likes