<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>


1 The Stack

This short tutorial will introduce you to the Forth stack.

1.1 What is the Stack?

The stack is used to carry data between words (Forth speak for sub-routines). Forth does have variables that can be used to hold data, but using the stack can be much more efficient, and faster.

The stack is only used for holding for holding numbers. Each 'entry' on the stack is called a cell. A cell is 16 bits in TurboForth.

1.2 Putting Numbers On the Stack

To put a number on the stack, simply type the number. For example, with the cursor blinking on the TurboForth command line, just type:

  99

And press enter. TurboForth will respond with ok:1

The number 1 after the ok simply means that there is one number (99) on the stack.

Now type 59 and press enter. TurboForth responds with ok:2 - there are now two numbers on the stack.

The stack works like a stack of plates in a restaurant. You can only deal with the top most plate. Think of stack entries as plates with numbers written on them. In our example, the stack now looks like this:

  59
  99

59 is the top-most (the 'most accessible') stack value.

1.3 Taking Numbers Off the Stack

Many words in the Forth language are designed to work on the top-most stack value. Often, in doing so, they consume that value at the same time.

For example, the "word" to display a number (which is on the top of the stack) is . (dot). So, just type

  .

Then press enter. TurboForth displays 59 ok:1 - the 59 was the top-most value on the stack, and the 1 after the ok means there is one value remaining on the stack (in other words, the 59 was consumed by .)

Now type . again. TurboForth responds with 99 ok:0 - our stack is now empty.

1.4 Moving Numbers Around the Stack

Sometimes, you might want to access numbers "further down" the stack. There are a number of words that can manipulate the stack for you. One such word is SWAP. SWAP swaps the top two stack items. So, if you type:

  99 59

You get two numbers on the stack, with 59 at the top of the stack.

Now type:

  SWAP

Now, type . and press enter. TurboForth displays 99 - SWAP moved the 99 to the top of the stack. Now type . (and press enter) again. TurboForth displays 59.

A useful word is .S (dot S) which lets you see the stack without removing or changing the data on the stack. For example:

  100 99 5 77 21 24 .S

Displays

  100 99 5 77 21 24 <--TOP

Notice how TurboForth shows you which value is the top of the stack.

Now type:

  SWAP .S 

And you will see

  100 99 5 77 24 21<--TOP

See? The top two items were swapped.

Try:

  DUP .S

DUP means DUPlicate the top stack item.

The language reference has a section on the stack manipulation words.

<-- Back to Tutorials


<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>