Edit this page

herkforth Edit Time Tutorial

First you will need to build herkforth.

Then run herkforth.

You will now see the herkforth editor.

In this tutorial we won't be using the source code (the yellow/green/red/pink words in the middle of the screen). So you can just ignore it, and don't worry if you change something there (eg by hitting space) because we won't save in this tutorial.

We will however be paying quite a bit of attention to the stack, which is displayed near the top of the screen. It should look like this:

stack: 1 2 3 4 5

Pretty much everything you do in herkforth uses the numbers on the stack. Everything that uses the stack uses the number(s) from the right end (called the "top" usually).

Note: In this tutorial we won't use the space bar. After each word/number we type we'll hit enter. Enter tells herkforth to do whatever you've typed right now.

Let's add another number to the stack. type 43 and press enter.

Now the stack should look like this:

stack: 1 2 3 4 5 43

Another way to get a number on the stack is to duplicate the top item. Type dup and press enter.

stack: 1 2 3 4 5 43 43

Now let's add a 4: type 4 and press enter.

stack: 1 2 3 4 5 43 43 4

Now let's subtract. - (minus) subtracts the top item (the 4 in this case) from the number below it. Removes both from the stack, and leaves the result. Type - and press enter.

stack: 1 2 3 4 5 43 39

Now divide. herkforth uses the symbol / for divide. divide (like minus) takes two numbers off the stack, does it's calculation, then puts the result on the stack. / divides by the number on top. Type / and press enter.

stack: 1 2 3 4 5 1

The stack only holds integers, so the result of the devision was truncated. It is not rounded to the nearest integer, but always rounded towards zero. For example if you divided 100 by 101 the result would be 0.

Tip: A good way to remember which number is subtracted from which, and which is divided by which, is to imagine placing the symbol (- or /) between the last two items on the stack. Thus in the subtraction above, you could imaging placing the - between the last two items on the stack (43 - 4). Forth generally works this way.

It sometimes happens that you end up with a number on the stack that you don't want. We've had all this fun, and calculated a magnificent 1 on the stack. And we're done with it. Type drop and press enter.

stack: 1 2 3 4 5

Right back where we started.

Press SHIFT-Q to quit back to GNU/Linux.

You may want to proceed to the other herkforth tutorials

See Also

herkforth tutorials

herkforth

forth

Edit this page · home ·