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
+placeit takes theaddr ureference for "world " from the stack and then appends "world " to "hello ". So if you tryYou should see
hello world okAt this point all of your
placeor+placewords 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
padagain it pushes the address thatpadrepresents to the stack. So the next+placedoesn'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
+placehas the right arguments on the stack and works as expected.