6.12 User-defined Stacks

Gforth supports user-defined stacks. They are used for implementing features such as recognizer sequences, but you can also define stacks for your own purposes. And these stacks actually support inserting and deleting at both ends, so they are actually double-ended queues (deques). In addition, they support inserting and deleting in the middle.

In Gforth the stacks grow as necessary, but the interface is designed to also support resource-constrained systems that allocate fixed-size stacks, where exceeding the stack size results in an error. So you should provide the size parameter accordingly.

A stacks is represented on the data stack by a cell.

stack ( n – stack  ) gforth-experimental “stack”

Create an unnamed stack with at least n cells space.

stack: ( n "name" –  ) gforth-experimental “stack-colon”

Create a named stack with at least n cells space.

stack> ( stack – x  ) gforth-experimental “stack-from”

Pop item x from top of stack.

>stack ( x stack –  ) gforth-experimental “to-stack”

Push x to top of stack.

>back ( x stack –  ) gforth-experimental “to-back”

Insert x at the bottom of stack.

back> ( stack – x  ) gforth-experimental “back-from”

Remove item x from bottom of stack.

+after ( x1 x2 stack –  ) gforth-experimental “+after”

Insert x1 below every occurence x2 in stack.

-stack ( x stack –  ) gforth-experimental “-stack”

Delete every occurence of x from anywhere in stack.

set-stack ( x1 .. xn n stack –  ) gforth-experimental “set-stack”

Overwrite the contents of stack with n elements from the data stack, with xn becoming the top of stack.

get-stack ( stack – x1 .. xn n  ) gforth-experimental “get-stack”

Push the contents of stack on the data stack, with the top element in stack being pushed as xn.