Scope
In the previous examples, notice that the variable, x, is declared at the top of the program, before the setup and draw functions. Notice what happens if you put it inside the draw loop - it resets to 0 every frame, so the circle never moves. This is called scope.
A Variable declared inside a function only exists inside that function. At the end of the function, it disappears. Use this if the variable is used for something temporary, and doesn't need to store data permanently or keep track of anything.
A variable declared outside of any functions is called global. A global variable persists the whole time the program is running, and is shared by all functions.
void setup()
{
size(500,300);
}
void draw()
{
int x=0; // putting the variable here makes it reset to 0 every frame
background(0);
x=x+2;
if ( x > 500)
{
x = 0;
}
ellipse(x,100,20,20);
}
Here's another scope example. This program won't run, it'll give an error saying that the variable is unknown.
void setup()
{
int a = 10;
println ("print the variable from inside the setup function");
println(a);
}
void draw()
{
println("try to print the variable inside the draw function");
println(a);
}