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.
The require() function only runs the module once and then every other call is given a reference to the same return object. You aren’t wasting memory by requiring the same module from multiple scripts since they all end up referencing the same object.
In situation where you need data be shared for more than 3-4 scripts and it’s not big you can freely use it, personally for bigger data i use modules as they are more specific, but with player afk or smth it’s way to go as long as it’s efficient
So, this is half true. Many practices are also to keep you from bad habits, and firce you to grow in a specific way.
If you learn doing bad technique its much harder to change your habit.
There is a balance to be struck though of which i will admit.
ImO my balwnce is, if i know i did something bad, i leave a comment saying “this is bad you did a bad no dont justify it fix it later when you can, stop being bad”
That being said there a few rules that are universal. 2hen it comes to coding habit.
Generallt speaking bad habits will lead to you hitting a wall in your ability to either maintain code and or grow as a coder.