EXIT example
The following function counts the number of words in a string by counting spaces between words. Multiple spaces between two words are counted as a single space and therefore a single word:
function wordCount(cArg)
local nRet, cRemain, nPos
nRet = 0
cRemain = ltrim( trim(cArg))
do while "" # cRemain
nRet++
nPos = at(" ", cRemain)
if nPos == 0
exit
else
cRemain := ltrim(substr(cRemain, nPos))
endif
enddo
return nRet
The condition in the DO WHILE loop is really needed only once, the first time the loop is entered. It makes sure that there is some text to search through. If the argument is an empty string or all spaces, the loop is not executed and the word count is zero. After the first loop, it is used simply to keep the loop going, since there would always be text to check.
The loop is terminated when there are no more spaces in the string. This is determined by the return value of the AT( ) function. Because the position returned is out of range for the SUBSTR( ) function, it should be called if there are no more spaces in the string. By using EXIT, the loop is immediately terminated once no more spaces are found. Execution continues with the RETURN statement following the DO WHILE loop.