FAQ
Cover
This is the archive Discourse for the Processing (ALPHA) software.
Please visit the new Processing forum for current information.

   Processing 1.0 _ALPHA_
   Programming Questions & Help
   Syntax
(Moderators: fry, REAS)
   variable scope
« Previous topic | Next topic »

Pages: 1 
   Author  Topic: variable scope  (Read 219 times)
kevinP

Email
variable scope
« on: Jan 17th, 2004, 10:32am »

Hi all,
 
Playing around and looking at the sin functions, etc. (who knew that math might be so useful), I figured out how to sweep a line segment around its endpoint.
 
I put the variable "center" between setup() and loop(), thinking that it really needs to only be calculated once. But when I do this, I can't access the system variable "width" (see code).
 
Code:

// sweep a line segment in a circle around its endpoint
 
void setup() {
  size(200, 200);
  stroke(255);
  framerate(25);
  smooth();
}
 
int center = 100;   // this works!
// int center = width/2;  // this doesn't...
 
float a = 0.0;
float inc = TWO_PI/180.0;
 
void loop() {
  background(32);
  float x = cos(a)*80.0;
  float y = sin(a)*80.0;
  stroke(255);
  line(center, center, center + x, center + y);
  a += inc;
  point(center, center);
}

 
It also works if the center assignment is inside loop(), but doesn't this mean that "center" is being re-evaluated every frame? (I know, I should write a "LineSweep" class.)
 
Does loop() only really loop those things that need it?
 
-K
 

Kevin Pfeiffer
REAS


WWW
Re: variable scope
« Reply #1 on: Jan 17th, 2004, 9:07pm »

programs don't read from top to bottom, but in a pre-specified order. everything outside of setup() and loop() is evaluated first when the program begins. setup() is evaluated second, and then loop(). the "width" variable is set from the values put into the size() function. if you want to set a variable based on the width, you will need to assign it after size() is called. for example, declare "int center;" where it is now, but don't assign it until inside setup().
 
Code:

int center;
float a = 0.0;  
float inc = TWO_PI/180.0;  
 
void setup() {  
  size(200, 200);  
  center = width/2;
  stroke(255);  
  framerate(25);  
  smooth();  
}  
 
void loop() {  
  background(32);  
  float x = cos(a)*80.0;  
  float y = sin(a)*80.0;  
  stroke(255);  
  line(center, center, center + x, center + y);  
  a += inc;  
  point(center, center);  
}  

 
 
Pages: 1 

« Previous topic | Next topic »