Question

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?

Was it helpful?

Solution

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 the addr u reference for "world " from the stack and then appends "world " to "hello ". So if you try

s" hi " pad place 
s" hello " pad place
s" world" pad +place

//Display the string at pad
pad count type

You 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 run

s" hi " pad place 
s" hello " pad place
s" world" pad 
+place

//Check the stack
.s

You will see an empty stack.

Now when you use pad again it pushes the address that pad 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

s" hi " pad place 
s" hello " pad +place
s" world" pad +place
pad count type

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top