Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can _G be used in a localscript?

Asked by 10 years ago

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

Log in to vote
4
Answered by 10 years ago

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.

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 BlueTaslem 18071 — 10y
0
Thanks! It really helped! TurboFusion 1821 — 10y
Ad

Answer this question