Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can _G be used in a localscript?

Ok so I've made a script that uses _G, but if _G is placed in a localscript, does that mean that whatever variable _G is assigned to, it will be global to any script in the player? Or will it be available to any localscript in the game?

1 answer

✓ Accepted answer

There are multiple _G tables in the game. This number depends on the number of Players in the game. Each client has its own _G. If you access _G in a server script, and try to index a value set by any of the clients, you will get a nil value. The server can only use values set by other server scripts, and each client can only use values set by that particular client. If you want to communicate from the server to a client, use Remote Events/Functions

For example, say I have two players, Player1 and Player2. And I run the following code on Player1:

_G.Player1 = "Player1"

Then I run this code on Player2:

_G.Player2 = "Player2"

Finally, I run this code on the server:

_G.Server = "Server"

Now, I take the following script and run it for both players and for the server:

local ownName = "Name" --This would be changed to Player1, Player2 or Server depending on where the script was.
print(_G.Player1, ownName)
print(_G.Player2, ownName)
print(_G.Server, ownName)

You will find that each script can only print one of the three values we set. This is due to _G being different for each client and for the server.

2 comments

0

TL;DR: _G works in LocalScript's, but it's only the same object for all local scripts on that client; server scripts get their own shared _G

0

Thanks! It really helped!

This discussion is preserved as it was. New answers, comments, and votes are closed.