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?
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?
About the author
Torque Owner Jason Cahill
Default Studio Name
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.