76 lines
1.9 KiB
Markdown
76 lines
1.9 KiB
Markdown
# Using Variables
|
|
|
|
Variables let you name values and share data between steps. They are global -- any step can read what another step wrote.
|
|
|
|
## Store and Fetch
|
|
|
|
`!name` stores the top of the stack into a variable. `@name` fetches it back. Variables spring into existence when you first store to them. Fetching a variable that was never stored returns 0.
|
|
|
|
```forth
|
|
10 !x ;; store 10 in x
|
|
@x ;; pushes 10
|
|
@y ;; pushes 0 (never stored)
|
|
```
|
|
|
|
## Store and Keep
|
|
|
|
`,name` stores just like `!name` but keeps the value on the stack. Useful when you want to name something and keep using it:
|
|
|
|
```forth
|
|
440 ,freq sine snd . ;; stores 440 in freq AND passes it to the pipeline
|
|
```
|
|
|
|
Without `,`, you'd need `dup`:
|
|
|
|
```forth
|
|
440 dup !freq sine snd . ;; equivalent, but noisier
|
|
```
|
|
|
|
## Sharing Between Steps
|
|
|
|
Variables are shared across all steps. One step can store a value that another reads:
|
|
|
|
```forth
|
|
;; step 0: pick a root note
|
|
c4 iter 7 mod + !root
|
|
|
|
;; step 4: read it
|
|
@root 7 + note sine snd .
|
|
```
|
|
|
|
Every time the pattern loops, step 0 picks a new root. Step 4 always harmonizes with it.
|
|
|
|
## Accumulators
|
|
|
|
Fetch, modify, store back. A classic pattern for evolving values:
|
|
|
|
```forth
|
|
@n 1 + !n ;; increment n each time this step runs
|
|
@n 12 mod note sine snd . ;; cycle through 12 notes
|
|
```
|
|
|
|
Reset on some condition:
|
|
|
|
```forth
|
|
@n 1 + !n
|
|
( 0 !n ) @n 16 > ? ;; reset after 16
|
|
```
|
|
|
|
## When Changes Take Effect
|
|
|
|
Within a single step, you can read back what you just wrote. But variable changes only become visible to other steps after the current step finishes executing. If step 0 writes `10 !x` and step 1 reads `@x`, step 1 sees the value from the previous iteration of step 0, not from the current one running in parallel.
|
|
|
|
## Naming Sounds
|
|
|
|
Store a sound name in a variable, reuse it across steps:
|
|
|
|
```forth
|
|
;; step 0: choose the sound
|
|
"sine" !synth
|
|
|
|
;; step 1, 2, 3...
|
|
c4 note @synth snd .
|
|
```
|
|
|
|
Change one step, all steps follow.
|