2.5 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 print ;; leaves 6 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.
Removing Words
forget removes a user-defined word from the dictionary:
: double dup + ;
3 double ;; 6
"double" forget
3 double ;; error: unknown word
This only affects words you defined with : ... ;. Built-in words cannot be forgotten.
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.