I found a game I wrote in LISP a few years back where I used no global variables. Instead I put everything in a hash table "world" that I passed as an argument to various update functions that returned a new hash table with the new values. There was only one assignment statement of the form (setf world (update world)) in the main game loop.
The game ran like crap. Should I have used global variables instead?
>>59942428
>(setf world (update world))
Why would you use SETF if your (update world) function returns a new world value?
Obviously if you go with the "copy everything" mentality you incur a speed and memory penalty for it. But your (should) have fewer bugs.
Global variables are not always evil, the point is to segregate functions that modify them from functions that do not modify anything outside of themselves.
Also, your game could have had other issues besides a giant hash that would cause it to run slow.
>>59942428
There's some pretty good discussion about this in K&R, isn't there one in your religion's scripture?
>>59942428
global vars are ALWAYS evil because they introduce global state. Managing state is a hard problem, and if it's even global - u r in some deep, deep shit.
Usually, if you ever need to access some state globally - you want a DB. If you want it in memory - add caching.
Simple as that.
>>59942547
But since in a game most functions modify the game state, wouldn't it be simplest to make everything a global variable and have all functions directly modify the global variables and return nothing?
>>59942428
Yes global variables are always bad outside of C (not C++). Yes, your "solution" was bad. I would look into component based design and event based messaging. Branch out from there
>>59943330
global vars are ALWAYS bad, no exclusions. You're right in the remaining part of your post, though
>>59942428
Basically they are only useful as locks in parallel computing.
>>59943685
which is also a bad practice. Sane programmers use CSP or actor model
>>59942428
Global variables are good for your code, it makes it easier to share them across the whole program scope.
I am a certified Javascript Senior Architect.