From Rosetta code, I'm using the following as a way to concatenate strings in Forth.
s" hello" pad place
pad count type
s" there!" pad +place
pad count type
Using this code, I'd like to be able to concatenate multiple strings together. However, the following fails on Gforth
s" hi " pad place
s" hello " pad place
s" world" pad
+place
pad +place
pad count type
From my basic Forth exposure, I see the code as putting three strings on the stack, then appending the string on the top of the stack with the string below it, then appending the new string on the stack again with the bottom one.
Why does this code underflows on the last +place? Is there a way around this?
Your second snippet copies "hi " to the memory location
pad
, then copies the "hello " to the same location (overwriting "hi ").So when you try the first
+place
it takes theaddr u
reference for "world " from the stack and then appends "world " to "hello ". So if you tryYou should see
hello world ok
At this point all of your
place
or+place
words have used up all of the string references on the stack. To check this if you just runYou will see an empty stack.
Now when you use
pad
again it pushes the address thatpad
represents to the stack. So the next+place
doesn't have a string reference on the stack for it to copy, and so it fails.To fix this you want something like this instead
In this code the "hello " does not overwrite the "hi " and is instead appended to it, so the next
+place
has the right arguments on the stack and works as expected.