by showmyiq » Tue Apr 09, 2013 10:06 am
There are three loops function in PostScript.
1)number { block } repeat – this will repeat the block of the function number times. For example if you type – 10 { stack } repeat – this will print the current stack 10 times.
2)start inc end { block } for – this is the for loop. It will start from value – start, and ends at value end. The inc value defines the step for each iteration going from start to end. For example if you type – 10 -1 0 { stack } for – this will print the stack 10 times, but stack will be changed!
You should pay attention here – with the for loop you are going not only counting the iterations and defining the iteration step with the inc variable, but you are going to push the inc variable in the stack too. Try the following source:
97 98 99 100
1 1 4 { stack } for
This will be the result:
1
100
99
98
97
2
1
100
99
98
97
3
2
1
100
99
98
97
4
3
2
1
100
99
98
97
As you can see we pushed in all the iteration temp values into the stack. This is very useful when we are making some more sophisticated programs, but in this simple program ( just to print the current/operational stack 4 times) is not desired. How can we avoid that? Just include pop command at the beginning of the stack.
97 98 99 100
1 1 4 { pop stack } for
Now the results are exactly those we needed!
3) { block } loop – this loop will loop the block function infinite times. So it’s very important to include a break command somewhere in the block function when you want to end the loop. A source code like – { stack } loop – is very undesirable! This will loop forever…
But if we write something like that:
1 2 3
{ stack 2 1 gt { exit } if } loop
The stack will be printed once, then the if condition will be triggered, because 2 is greater than 1 and exit command will be launched. The command exit defines the end of the loop.
Here is one example I have scripted myself – a program that take the top element of the stack (some random integer value), and generate the first Nth Fibonacci numbers.
/fib
{ dup 1 eq { pop 1 } {
dup 2 eq { pop 1 1} {
1 1 3 -1 roll
dup 2 sub exch pop
{ 2 copy add} repeat
}ifelse
}ifelse
} def
100
fib
stack
Can you make the same program using for loop?
Can you optimize the source?
Just play with PostScript in order to learn. The best learning model is practicing!