Rick,
I wish I knew what was going wrong on your system. I copied the code as you posted it, fiddled with it until I found the problem, tested it and so on.
In other words, I'm not just making assertions here, but actually testing everything.
The code fragment you just posted looks wrong. I can't really tell, maybe the forum software is doing something goofy. There should be a space between the parentheses.
Here's the breakdown: spacecount is a proc that returns the number of spaces in any given string. The first thing I do to a string is append a space to the end of it. Thus, the number of spaces=number of words.
1st, the spacecount proc puts a zero on the stack. This is the number of spaces. I'll add 1 to it each time I find a space. So now I have the string and 0 on the stack. "exch" swaps them. Next comes a space: ( ). That's a single space character inside parens. So the stack looks like:
space
string
zero
Next is the search. I'm searcing for a space in the string. (note that this search occurs within a loop).
Search returns a boolean (true or false). If true (it finds a string), it splices the string into 3 pieces and leaves them on the stack: post match pre bool. In other words, the substring after the search string, the search string, the substring before the search string, and "true".
If false, it returns the entire string and false: string false.
At this point , the ifelse fires. If true, look what happens:
pop 3 -1 roll 1 add 3 1 roll
What's on the stack to be popped off? The boolean is gone, the ifelse consumed it. So it's the "pre" substring. Our first word/space. Throw the word away (pop!).
Our stack now looks like:
match
post
0
3 -1 roll "rolls" the 0 to the top. Next is "1 add". Add 1 to 0, we found a space. Stack is:
1
match
post
3 1 roll rearranges the stack:
match
post
1
Now we repeat the loop. We go back to "search", searching "match" (a space character) in "post" (the rest of our string).
We keep looping until we find no more spaces, the false section fires, which pops of the remaining string (which is empty at this point) and exits the loop: pop exit. The end result is a number on the stack representing the number of spaces in the string.
This is used as an argument for the "repeat" portion of the "P" procedure.
Thomas D. Greer