Search code examples
variablesprocessingbuilt-in

Built-in variables not usable in certain cases (Processing 3)


I've been building a program with Processing 3 the last several days (first time going back to Processing since Intro to Computer Science in 2009) and kept having this issue:

public class PolarMap {
    ...
    PVector[][] mapping = new PVector[width][height];
    PVector[][] cartesian = new PVector[width][height];
    PVector cart = new PVector();
    PVector polar = new PVector();

    /**
    Maps every pixel on the cartesian plane to a polar coordinate        
    relative to some origin point.
    */
    public void Map(float originX, float originY){
        for (int x=0; x < width; x++){
            for (int y=0; y < height; y++){
            ...
            cart.add(x, y);
            polar.add(r, theta);
            mapping[x][y] = polar; ***
            cartesian[x][y] = cart; 
      }
    }
  }
  ...
}

On the line with the ***, I would always get an Array Index Out Of Bounds thrown. I searched SO, Reddit, and Processing's own documentation to figure out why. If you're not familiar with Processing, width and height are both built-in variables and are equal to the number of pixels high and across your canvas is as declared in the setup() method (800x800 in my case). For some reason, both arrays were not being initialized to this value--instead, they were initializing to the default value of those variables: 100.

So, because it made no sense but it was one of those times, I tried declaring new variables:

int high = height;
int wide = width;

and initialized the array with those variables. And wouldn't you know it, that solved the problem. I now have two 800x800 arrays.

So here's my question: WHY were the built-in variables not working as expected when used to initialize the arrays, but did exactly what they were supposed to when assigned to a defined variable?


Solution

  • Think about when the width and height variables get their values. Consider this sample sketch:

    int value = width;
    
    void setup(){
       size(500, 200);
       println(value);
    }
    

    If you run this program, you'll see that it prints 100, even though the window is 500 pixels wide. This is because the int value = width; line is happening before the width is set!

    For this to work how you'd expect, you have to set the value variable after the size() function is called. So you could do this:

    int value;
    
    void setup(){
       size(500, 200);
       value = width;
       println(value);
    }
    

    Move any initializations to inside the setup() function, after the size() function is called, and you'll be fine.