So I know that using global variables is bad practice (because they can make program state unpredictable among other things) but I was wondering if there is ever a good case for using them.
For example, in the game I’m currently working on I used a global variable for two tables. One which stores the current state of the player (AFK, escapee, hunter, etc) and one which stores the player name which allows me to access the player from the server. (For example I can anchor the primary part of a specific player).
I only change these two tables when a new round is started, when a player leaves, when a player joins, or when they put themselves into an AFK state.
Would this still be considered a poor use of a global? And if it is what should I do instead so that these tables are accessible to all of the server scripts?
No. I use _G and Shared all the time, (Shared is essentially just _G but a different global table).
I use it to store the frameworks I build and the various modules attached to those frameworks, This allows me to go into any game and access my running modules via the F9 game console; As for exploiters, various metamethods hooks and cleaver coding can get around and really frustrate the exploiters.
So if there’s absolutely no reason to use it then why is it still available in Roblox studio? And why is available for use in many other programming languages?
Because so many people used it in the past, Roblox can’t just simply remove or deprecate it because it would break many older games that relied on it, as well as making some people upset. If so many other programming languages utilize _G or something similar, then it’s because it’s useful or has an advantage over alternatives.
Keep in mind that you are running a game engine, not a programming language. There are many implemented alternatives and the community generally sides with those.
In the future, refrain from bumping an old topic like this. You could’ve tested in studio and pasted that and that’d take less time than waiting for me to respond as well. But yes, you can use _G effectively. However make sure the module loads first to avoid nil values.