[gameprogrammer] Re: Variable Scope and g , l ?

  • From: Carlos Lopez <charlie.lobo@xxxxxxxxx>
  • To: gameprogrammer@xxxxxxxxxxxxx
  • Date: Wed, 1 Dec 2004 20:25:32 -0600

Global variables are variables that are accesible from any point in
code freely (as long as they have been declared previously).
Local variables are only accesible in their scope.
In a module the scope is all functions and objects within that module.
If the local variable is declared within an object then it's scope is
within the object and all it's functions.
The same applies to functions.
Local variables can only be used normally within their scope. This is
the main difference between local and global variables. Because of
this, also, global variables have to be delcared out of functions and
so (if I remember well VB does need you to declare them out of the set
of functions at the beggining of code) but they can be used anywhere,
but you can only have one name for global variables.
Local variables are declared within whatever they are used for and
each one is separate of the other, so you can have two local variables
with the same name as long as they are in different scopes because
they are really different variables.

Local variables have ways to "escape" their scope though. This only
works for public variables, so if I declare a public variable X within
object Y I can just do this within anywhere in the class Y

X=value

and if I have an instance of the object Y called YI I can set the
version of the variable X within YI (because since different objects
don't share scopes and may have variables with the same name yet
different values) to a value outside of the object as the next

YI.X=value

Of course this is very dangerous for many values since one my
accidentally change it, so to prevent this people make local variables
within a class private. They are still different instances of the
scope and the variable in each instance of the class/object but you
can't access it as I did above. So instead one uses functions to
handle the variables so I'd have a function like the next:

class Y
private int X
public function setX (int nX)
X=nX
end
endclass //it was something like this, sry if it's different normally
the program does it for me.

We can access X normally withing setX(int) because we are within the
scope of the object/class, but outside of the scope, because it's
private it's invisible. This way it's safer to control variables
within the function and handle mistakes.
Finally I don't know if you do this but the function there is public,
that is because all functions can be public or private and work like
local variables, yet there is no such a thing as global functions
(that I know of).
Hope it helps and I didn't give a bit tad too much, normally we
already understand and use the concepts just not the names.


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: