You might want to copy one string variable to another. There is a special word for that, named 'CMOVE'. It takes the two strings and copies a given number of characters from the source to the destination. Let's take a look at this example:
32 string one \ define the first string 32 string two \ define the second string " Greetings!" one copy \ initialize string one count \ get the length of string one 1+ \ account for the terminator! two swap \ get the order right cmove \ copy the string two count type cr \ print string two
The most difficult part to understand is probably why and how to set up the data for 'CMOVE'. Well, 'CMOVE' wants to see these values on the stack:
source destination #chars
With the expression:
We get these data on the stack:
But the terminator hasn't been accounted for so far. That's why we add:
So now this parameter has the right value. Now we have to tell 'CMOVE' where to copy the contents of string one to. If we simply add:
The data is not presented in the right order:
source #chars destination
So we add the extra 'SWAP' in order to get it right. Of course you may define a word that takes care of all that:
: copy$ swap count 1+ rot swap cmove ; 32 string one 32 string two " Greetings!" one copy two copy$
You may wonder why we keep on defining words to make your life easier. Why didn't we simply define these words in the compiler instead of using these hard to understand words?
Well, 4tH is derived from Forth and we wanted to stay as compatible as possible. That means if you have a good knowledge of both 4tH and Forth you can write programs that can be ported to full-fledged Forth compiler. Much later we will give you tips on how to do that.