schemegimpscript-fu

Nested while loop in Scheme with Gimp?


I'm writing a Gimp Script-Fu script, and trying to use a nested while loop. x is set to 15, y is set to 30. y loops up to 35, yet x stays at 15 and the loop quits. What is wrong here? Why is the value of x not changed?

(while (< x 20)
  (while (< y 35)    
    (gimp-message (string-append (number->string x) "-" (number->string y)))
    (set! y (+ y 1)))
  (set! x (+ x 1)))

Solution

  • y is never being reset back to 0. Your code will increment y up to 35, then increment x 20 times, however on each subsequent increment of x y is still set to 35.

    If you wanted to go over each combination of values of x and y then you would need code more like this:

    (while (< x 20)
        (set! y 0)
        (while (< y 35)    
                (gimp-message (string-append (number->string x) "-" (number->string y)))
                 (set! y (+ y 1))
                )
        (set! x (+ x 1))
    )
    

    Here is a more complete example now that I've had time to work through this question with Gimp (I'm using print instead of gimp-message because I'm working in the console, but it should be interchangeable). To start I'm defining a function called SO that accepts the arguments, x, y that both represents pairs of min and max values:

    (define (SO x y)
      (let* ((x! (car x)) (y! (car y)))
        (while (< x! (car (cdr x)))
          (set! y! (car y))
          (while (< y! (car (cdr y)))
            (print (string-append (number->string x!) "-" (number->string y!)))
            (set! y! (+ y! 1))
          )
          (set! x! (+ x! 1))
        )
      )
    )
    

    Inside this function, I'm pulling out the first and last values of x and y (with (car x) and (car (cdr x)) then I'm using let* to create two inner variables calledx!andy!that I will be altering the value of (to remove side effects of havingxandy` change after the function is called). If you call this function like so:

    (SO '(15 20) '(30 35))
    

    You get the following output:

    "15-30"
    "15-31"
    "15-32"
    "15-33"
    "15-34"
    "16-30"
    "16-31"
    "16-32"
    "16-33"
    "16-34"
    "17-30"
    "17-31"
    "17-32"
    "17-33"
    "17-34"
    "18-30"
    "18-31"
    "18-32"
    "18-33"
    "18-34"
    "19-30"
    "19-31"
    "19-32"
    "19-33"
    "19-34"