Files
Cagire/docs/forth/definitions.md

2.2 KiB

Creating Words

One of Forth's most powerful features is the ability to define new words. A word definition gives a name to a sequence of operations. Once defined, you can use the new word just like any built-in word.

The Syntax

Use : to start a definition and ; to end it:

: double dup + ;

This creates a word called double that duplicates the top value and adds it to itself. Now you can use it:

3 double    ;; leaves 6 on the stack
5 double    ;; leaves 10 on the stack

The definition is simple: everything between : and ; becomes the body of the word.

Definitions Are Shared

When you define a word in one step, it becomes available to all other steps. This is how you share code across your pattern. Define your synths, rhythms, and utilities once, then use them everywhere.

Step 0:

: bass "saw" s 0.8 gain 800 lpf ;

Step 4:

c2 note bass .

Step 8:

g2 note bass .

The bass word carries the sound design. Each step just adds a note and plays.

Redefining Words

You can redefine any word, including built-in ones:

: dup drop ;

Now dup does the opposite of what it used to do. This is powerful but dangerous. Redefining core words can break things in subtle ways.

You can even redefine numbers:

: 2 4 ;

Now 2 pushes 4 onto the stack. The number two no longer exists in your session. This is a classic Forth demonstration: nothing is sacred, everything can be redefined.

Practical Uses

Synth definitions save you from repeating sound design:

: pad "sine" s 0.3 gain 2 attack 0.5 verb ;

Transpositions and musical helpers:

: octup 12 + ;
: octdn 12 - ;

Words That Emit

A word can contain . to emit sounds directly:

: kick "kick" s . ;
: hat "hat" s 0.4 gain . ;

Then a step becomes trivial:

kick hat

Two sounds, two words, no clutter.

Stack Effects

When you create a word, think about what it expects on the stack and what it leaves behind. The word double expects one number and leaves one number. The word kick expects nothing and leaves nothing (it emits a sound as a side effect). Well-designed words have clear stack effects. This makes them easy to combine.