Game Development Community

Question on local vs global variables

by Mike Lilligreen · in Torque Game Builder · 02/15/2006 (2:59 pm) · 1 replies

Since I have no formal training in programming, just wondering if there is a recommended way to handle using variables. For example, I have a function in which I set a local variable (say %size) which holds the size of a sprite I just created. Within that same function I call another function and pass it %size. From what I understand after both functions are done, %size gets destroyed.

I could also create a global $size in the first function and have the second function use that. Which method is generally a better way to handle variables if either way gives the same result? Would there eventually be a performance drop in the game if too many global variables over time were created or is it a rather minor issue for todays computers?

#1
02/15/2006 (4:31 pm)
The choice of using locals vs. globals is simply one of code maintenance, readability, and support. Global variables, when used incorrectly (meaning constantly), tend to create a "spagetti code" effect where no one else can easily tell what's going on. For example, your scenario creates a global variable called $size. Where are all of the places that it could get set? What happens if one of those places sets it incorrectly? How many places are now broken?

Local variables, on the other hand, scope the location in the source code where they can have an effect, and therefore scope the kinds and volume of bugs you can have. In general, you should always use local variables for keeping track of any work that needs to happen within a single function. You should not attempt to share easily obtainable information in a global and use it between functions because it can become very tedious to try and find the source of a bug.

For most things, you should not need global variables within your game. As a best proactice, you should try to limit your usage of globals unless it's really necessary.