Scoping in recursive functions does not work how I expected: how does it work?

Hello! I just made a variant of a sketch from Daniel Shiffmans book The Nature of Code which involves a recursive function. To modify the colors, I use a global variable, that gets incremented on every call of the function, but the incrementation only works for one of the two recursive calls:

https://www.openprocessing.org/sketch/429721

image

I expected the smaller circles on both sides to change through the color spectrum, but somehow only the right side changes. I suspect, I is related to how variable scoping works, but I can't wrap my head around it. Does somebody have an idea?

Answers

  • OK, after a little bit of thought, I understood how to make it work for this sketch: using colorstep as a function parameter and not as a global variabel. But I would still like to understand what went wrong with the variable approach.

  • edited May 2017 Answer ✓
    • As a global variable, colorstep is how many times drawCircle() was invoked times 4.
    • However, given the 100 limit from colorMode(HSB, 100);, once that value is reached, there won't be any further changes on the actual HSB color for all the rest of ellipse() drawn.
    • Given all calls to drawCircle() w/ passed augmented x + radius/2 happen before decreased x - radius/2, the right side circles get their HSB fill() color varying before the 100 threshold is reached.
    • And all the 1s from left side are stuck w/ 100 HSB reddish color.
    • BtW, although drawCircle()'s 3rd parameter is called radius, it's actually the ellipse()'s diameter. 8-X
  • Thank you for the explanation!

    Once I was on the wrong train of thought, the similar looking colors (0,100,100) and (100,100,100) led me to the wrong conclusion, that the variable did not increment at all on the left side.

    A working version of it is now here:

    https://www.openprocessing.org/sketch/429748

    Of course with diameter as 3rd parameter.

Sign In or Register to comment.