Forth Medium · Lesson 1 · On the house

Immediate words and STATE

Mark words immediate so they run while a definition compiles, read STATE to tell compiling from interpreting, and test immediacy with FIND. Lesson 1 is free — on the house.

Lessons · Forth Medium · Lesson 1 of 10 · On the house

Immediate words and STATE

Mark words immediate so they run while a definition compiles, read STATE to tell compiling from interpreting, and test immediacy with FIND.

Illustration for Forth
Lesson 1 is on the house.

The text interpreter has two modes. state @ is zero while interpreting and non-zero while compiling a colon definition. : switches to compiling; ; switches back.

While compiling, the interpreter normally compiles a call to each word it finds. A word marked immediate is the exception: it runs right away, even inside a definition. immediate applies to the most recently defined word.

Control words such as if, then, do, loop and ." are immediate. That is how they lay down branches and strings while the surrounding definition is being built.

An immediate word inside a definition runs once, at compile time. In the still, stamp prints [built] during the compile of greet, and calling greet twice prints only hello twice.

ANS find ( c-addr -- c-addr 0 | xt 1 | xt -1 ) takes a counted string and returns 1 for an immediate word and -1 for an ordinary one. pad place turns an address/length pair into a counted string at pad.

Words whose behaviour depends on state (state-smart words) are fragile: ticking them and running the xt later gives the interpret-time branch. Prefer separate words, such as ' and ['], over one word that checks state.

immediate and state

: mode ( -- ) state @ if ." compiling" else ." interpreting" then cr ;
: now mode ; immediate
now
: probe now 7 ;
probe . cr
: stamp ." [built]" cr ; immediate
: greet stamp ." hello" cr ;
greet greet
: kind ( c-addr u -- n ) pad place pad find nip ;
: f1 ; : f2 ; immediate
s" f1" kind . s" f2" kind . s" if" kind . cr
Match this when you type.

Quiz

What does state @ leave while a colon definition is being compiled?

Quiz

When does an immediate word used inside a definition run?

Quiz

What does find return for an immediate word?

Quiz

Why does greet greet print [built] only once?

Check

Match the still for: Immediate words and STATE.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.