The PostScript Stack

5.5 The PostScript Stack

You can find an elementary introduction to the PostScript stack in the introduction , so you might want look there first to familiarize yourself with the basic concepts.

It won't take long when you are programming in PostScript to come to a situation where you wish you had access to the element that is above the top element in the stack. Fortunately, PostScript provides a set of commands that help you manipulate the stack. These commands can be thought of comprising three different classes: those that rearrange the stack, those that add copies to or delete elements from the stack, and those that give information about the stack.

Perhaps most useful for debugging and for teaching is the "stack" command. This prints a copy of the stack on the screen without affecting the contents of the stack. You can also see the top element with "=", but this also removes the element. Use "dup" with "=" to non-destructively view the top element. You can see how deep the stack is from the ghostscript prompt, as shown in the introduction , and you can also put the depth of the stack on the stack with the "count" command.

Rearranging the stack is done with the "exch" and "roll" commands. The "exch" command swaps the top element with the one below it. It solves the delemma mentioned at the start of this section. You can move a group of objects on the stack with the "roll" command, which takes two parameters, n and j . The way to see what it does is to imagine the top n objects on a wheel. The parameter j indicates how many notches to "roll" the wheel. If j is 1, each object in the top n places in the stack shifts up by 1, except the top element that can't go any higher. Instead, it fills the nth position in the stack, thus filling the hole that was left behind. If j is 2 , this is equivalent to rolling with j=1 twice. You get the idea for j larger than 2. If j is negative, this rolls the stack down instead of up. You should see the example to make more sense of this.

The commands for copying or removing objects are much simpler. You can copy the top object with "dup", the nth object with "index", and the top n objects with "copy". Similarly, "pop" removes the top object, and "clear" empties the stack.

David Maxwell, who is still writing this, would like to hear your comments and suggestions. And remember, parts of this manual are based on P.J. Weingartner's work: A First Guide to PostScript.