This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2008-08-17 17:00:47

yambanshee
Scratcher
Registered: 2007-11-06
Posts: 500+

local variables

its probably a noob question, but what is the advantage of local variables?

Offline

 

#2 2008-08-17 17:30:40

the_guardian
Scratcher
Registered: 2008-03-16
Posts: 98

Re: local variables

I find it useful for keeping track of enemy statistics;  such as whether the enemy is visible or not.   If you look at the enemy sprites in my Guardian 3D game, you will see extensive use of local variables for speed, agression, agility, status, etc.  By using local variables, each enemy can have it's own "personality".


Guardian 3D!  http://scratch.mit.edu/projects/the_guardian/169865

Offline

 

#3 2008-08-18 02:30:34

Jens
Scratcher
Registered: 2007-06-04
Posts: 1000+

Re: local variables

I like the_guardian's excellent explanation about local variables allowing each sprite in a set of similar ones to have its own "personality"!

Another benefit is, that local variables are restricted in namespace only to other local variables of the same sprite (and in future versions of Scratch possibly to global variables as well). That means you can duplicate a working sprite (like an "enemy") without each of the clones sharing the same internal state, as it were if you would use global variables.

The biggest difference between global and local variables is, that local variables can be manipulated (set/changed) only by the sprite they were created for. Other sprites may "read" their value (using the variable-sensor block), but cannot change them.


Jens Mönig

Offline

 

#4 2008-08-18 05:47:14

SonicPopsDad
Scratcher
Registered: 2008-07-30
Posts: 41

Re: local variables

Even if you have 10 enemy space ship sprites, and you want them all to behave in the same way, it's much better to code them using local variables rather than global variables wherever possible:

You create 1 enemy, with global vars 'status 1' etc etc and duplicate it a further 9 times.

If you've used global vars for everything, you then need to go into each, remove all the references to the  'status 1', create a global 'status 2' and insert that into the scripts... and do it for each sprite.  It's a tedious job!

If you used local vars then you've got nothing to do!  smile

You may need to do some clever(er) coding though... as you can't change local variables remotely (you can only inspect them using that sensor block) you may have to broadcast to specific sprites to tel them to change values.
This in turn may lead to timing problems (I think there's a slight lag using broadcasts) so you may need to use global vars after all... just try hard to use them only when absoulutely necessary!

Last edited by SonicPopsDad (2008-08-18 05:47:52)

Offline

 

Board footer