12.9 Application stacks. 4tH 4tH Forth compiler
Oglas
Oglas
CHAPTER 12. STANDARD LIBRARIES
12.9
Application stacks
175
Did you ever feel like a second return stack would be nice? Well, you can. As a matter of fact you can have several dedicated stacks. It’s quite easy to use:
[needs lib/stack.4th]
16 array mystack mystack stack
234 mystack >a
456 mystack >a mystack a@ . cr mystack a> mystack a>
. . cr
\ allocate some space
\ convert it into a stack
\ push 234 on the stack
\ push 456 on the stack
\ examine top of stack
\ pop 456 from the stack
\ pop 234 from the stack
\ show the values
Wouldn’t it be nice to have a string stack too? Yes, 4tH provides that one too! It works the same way:
[needs lib/stsstack.4th]
1024 constant /mystack string mystack \ allocate some space mystack /mystack string-stack \ convert it to a string stack s" Hello" mystack >s s" World" mystack >s mystack s@ type cr mystack s> mystack s> type cr type cr
\ push string ’Hello’ on stack
\ push string ’World’ on stack
\ examine top of stack
\ pop ’World’ from the stack
\ pop ’Hello’ from the stack
\ show the values
But if you only need a single stack - but one you can monitor - there is another library member:
2048 constant /cstack
[needs lib/stmstack.4th] s.clear
s" Hello" >s s" World" >s s@ type cr s> s> type cr type cr s.error CSE.NOERRS = . cr
\ clear the string stack
\ push string ’Hello’ on stack
\ push string ’World’ on stack
\ examine top of stack
\ pop ’World’ from the stack
\ pop ’Hello’ from the stack
\ show the values
\ show the exit status
You can set the size of the string stack by defining ”/CSTACK” before including it. ”S.CLEAR” clears the stack and resets ”S.ERROR”. ”S.ERROR” is simply a value you can query or set according to your needs. If you cause an underflow or an overflow, the integrity of the stack is maintained.
Note there is a catch: when you’ve popped a string from the string stack, the string itself is untouched, so the address-count pair is still valid. However, if you push another string onto the same stack, the popped string is clobbered - so a kind of ’SWAP’ is out of the question.
There is another way to create one (or more) string stack without these disadvantages, called strstack.4th, but it is larger and slower. It works the same way as the first library member we presented.
Prenesi
Oglas