Don't understand the _G

yo i don’t understand how the _G works

game.Players.PlayerAdded:Connect(function(player)
	_G[player.UserId]["Stuffs"] = "test"
end)```
ServerScriptService.Script:3: attempt to index nil with 'Stuffs'

have a nice day
1 Like

You can access variables from different server side scripts.
If you have this in one script.

look the error it say its nil.

_G Can be used for Global Variables/Arrays. You can learn more about it at Lua Globals (It is at the bottom of the Page)

For example, You can declare the Variable at a certain script:

-- First script
_G.MyName = "Crunch"

And use it on another one! It’s recommended to yield (wait) for a small time as it may take a very small amount of time to be accessed.

-- Second Script
task.wait()
print(_G.MyName)

Using Global Variables (_G or shared) for holding/storing Data (or even manage it) is not the best idea. I recommend you taking a look at ModuleScripts to understand more about them, And if you’re looking towards saving data, I recommend you using ProfileService.

3 Likes

now it does make sense. _G can be used for Global Variables.

_G is just a shared table. You’re getting that error because _G[player.UserId] doesn’t exist because you’ve never created it anywhere

game.Players.PlayerAdded:Connect(function(player)
    _G[player.UserId] = {}
	_G[player.UserId]["Stuffs"] = "test"
end)

Think of _G as a normal table. Anything valid for a table would be valid for _G. The only difference is, it’s shared across every similar script in the game (so server scripts to server scripts, and local scripts to local scripts). Although this may be useful upfront, it can cause a lot of issues with your code as sometimes one script loads in before the other, and it so happens that that script uses _G, it might not be defined yet. Module scripts would be a munch, much better option.

The error you’re experiencing isn’t this problem I mentioned above, though. You’re just creating your tables incorrectly:

--> Incorrect
_G[player.UserId]["Stuffs"] = "test"

--[[ Visual example of what you're trying to do
    _G = {
        [player.UserId]["Stuffs"] = "test"
                           ^
you CAN'T do this when creating a table (what are you trying to index?)
    }
--]]

--> Correct
_G[player.UserId] = {["Stuffs"] = "test"}

--[[ Visual example of what you need to do
    _G = {
        [player.UserId] = {["Stuffs"] = "test"}
                        ^
         you CAN do this when creating a table
    }
--]]

This is true, although it’s misleading. Peope are going to think _G only works in server scripts. Make sure to be as specific as possible.

The “shared” variable which is a global exclusive to Roblox (not present in native Lua) serves the exact same purpose as “_G” does.

Important information regarding G_:
https://www.lua.org/pil/14.html