Question

I'm currently working on a small interpreter written in Forth. For a small optimization, I'm trying to have a word which creates compiled words. For example, something which behaves like this:

: creator ( -- a )
    :noname ( u -- u )
        10 + ;
;

10 creator execute .
>> 20 ok

I tried several approaches so far and non worked (naïve like above, switching in interpretive mode, trying to compile a string of Forth source). Is this actually possible?

Was it helpful?

Solution

When you write compiling words, you have to be very careful about which words execute at compile time, and which execute at runtime. In this case, 10 + runs at compile time, and will not be compiled into you :noname definition.

I believe this is what you want:

: creator ( -- xt )   :noname ( n1 -- n2 )
   10 postpone literal  postpone +  postpone ; ;

Also note that you may use CREATE DOES> in many cases. E.g. if you want your creator to accept a number which is used by the child word:

: creator ( n1 "name" -- )   create ,
   does> ( n2 -- n1+n2 )   @ + ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top