14.5 Closures. 4tH 4tH Forth compiler
Tangazo
Tangazo
CHAPTER 14. PREPROCESSOR LIBRARIES 244
Note you can use built-in macro’s or phony variables as long as you have wrapped them into a macro of your own. This library only uses register
1
, leaving you plenty of registers to play with.
14.5
Closures
Yes, you’re reading it correctly: use can use the preprocessor to turn an archaic, low level language like Forth into something very hip and modern. Closures are functions that carry their own, persistent variables along. Some call them ”a poor mans objects”. Defining a closure is very simple. It is almost like defining a structure: include 4pp/lib/closures.4pp
:: counter vars var: start
\ counter creation word
( n1 n2 addr --)
\ define closure data
\ initial value var: inc end-vars {
}
\ increment per call
\ only cells may be used!
this -> inc ! this -> start !
\ initialise closure
{: this -> inc @ this -> start dup ? +! ;}
\ assign default behavior
;
You can’t use ”colon” to define a closure, you have to use the ”double colon” notation.
Then you start defining the variables of the closure right away. Note you can only define cell variables . The rest is quite straight forward: instead of struct, you use vars.
Instead of using end-struct, you use end-vars to finish your data definition.
Then we start with the initalization routine. Note the first parameter of any closure routine is always its address (just like ’DOES>’), which is put on the stack by ”{” and accessible through ”THIS”. Any additional parameters follow after that. In this case, when creating the closure the initial value of the counter and its increment are set.
Finally, we define the run time behavior - that is the code which is enclosed by ”{:” and
”;}”. Done. Now let’s define a few closures of the ”COUNTER” type:
5 2 sets counter counter1 \ make a counter
That’s all? Yes, that’s all you need to do to create and initialize ”COUNTER1”. Now let’s call it: counter1 counter1 counter1
\ 5
\ 7
\ 9
First it will print ”5”, then ”7” and finally ”9”. Now let’s try another ”COUNTER:
13 3 sets counter counter2 counter2 counter2 counter2
\ make another counter
\ 13
\ 16
\ 19
Now that wasn’t too hard, was it? Ok, before you start asking stupid questions, consider this: wouldn’t you be better off with full fledged object orientation? If you answer this question with ”yes”, read on. You’re in for a surprise.
Pakua
Tangazo