The text interpreter has two modes. state @ is zero while interpreting and non-zero while compiling a colon definition. : switches to compiling; ; switches back.
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.

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
Quiz
Quiz
Quiz
Quiz
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.