Global variables have a serious issue on the client

I made a global variable in one local script:

_G.spectators = {}

and referenced it by a local variable in another local script and tried changing the table:

local spectators = _G.spectators
table.insert(spectators, player.Name)

However, the global variable _G.spectators did not change since I believe the local variable did not store a reference to it but a copy of it. This is not the case with globals on server scripts; assigning a global table to a local variable and changing it will work as the local variable stores a reference to it and not a copy of it.

Is there anyway to make globals have the same behavior on the client has well? Thanks.

Its Better to use a ModuleScript for this case.

_G only works on the Server since that is global while a LocalScript functions on the Local Player, Because of that, _G.spectators will be nil according to LocalScripts

with ModuleScripts, Both Server and Client can access it :slight_smile:

(Could be wrong tho)

1 Like

This is not true. Global variables work on both the client and server. Not just the server. It’s a matter of race condition.

If your script runs before the global variable is created, then it will be nil. To circumvent this, make sure the script that creates the global variable runs before the other scripts that use it.

Global variables are seriously bad to practise, and I’d advise you to use module scripts instead. They’re faster, easier to work with, have organizational value, and can be reused.

Yeah after looking again, You appear to be correct
Screenshot (105)

But changing a variable in a module script will not change it for other local scripts which call the module script.

The global variable works fine and isn’t nil, it’s just that I want to be able to use a local variable to refer to (not store) a global variable so that I don’t have to spell out _G.spectate all the time.