Quote: "I'm trying to get my head around this, so whenever a function is called, it has to run until it hits a ENDFUNCTION or EXITFUNCTION command?"
If you run the code I posted, you'll see that the countit() function gets run 11 times before ct(0)=ct(0)+1 is executed in myfunc(). myfunc() keeps restarting itself as long as the conditional:
IF LEN(s$)<10 THEN s$=myfunc( s$+"X")
is met.
Each time the function is called, the function address is stored on the stack (a temporary storage place in the computers memory) and the current line is managed by the program counter (PC). The PC keeps track of the current line and looks at the stack to see if there were any jumps that it has to return to. A function call is one such jump. A gosub and return is another such jump. A goto, is a jump without any kind of return - therefore the PC is set to the goto's destination without having to store anything on the stack.
In the case of your function, there are 11 jumps that occur before the PC can move on to ct(0) = ct(0) +1 . Once the PC has been able to move on to that line, it will reach the endfunction. Once this is hit, the PC will look at the stack and say "where was this call made from?"
If there is an answer, the PC will reset to the end point of the command on the line from where it was called (usually ends up being the next line after the call - but don't take this literally). Since ':' in BASIC can string multiple commands together, the PC doesn't necessarily have to return to the next physical line after the one it was called from:
a=0
b=20
gosub _add
end
_add:
inc a
if a<b then gosub _add : Print "a = ";a
return
In this example,
Print "a = ";a is executed after 19 recursive calls to _add. The : is a marker to tell the PC where to return. Each time the
Return is hit, the PC will look at the stack and ask if where the call came from. Every time the PC asks the stack a question, the stack gives the answer and reduces itself. It removes the top entry. In effect in the last example, after the stack has stored 19 calls, it will reduce that number by 1 call each time it is queried by the PC until there is no more information to give, at which time the PC will move beyond the function or the subroutine.
In this way, functions and subroutine calls can be nested within each other.
Now, there is only a certain amount of memory that the stack can use, so if you have a recursive call that gets nuts, or doesn't have a resolution, it's easy to crash the computer. That's one reason it's bad to use a GOSUB without a return. The stack might have information on it that never gets removed.
Loops might be subject to this as well. If you don't let the loop resolve, and you jump out of it with a goto for example, the stack may have information on it that never gets used (removed). That's why it's important to use EXIT to break out of a loop if you have to. I would bet that Exit clears the stack and resets the PC.
Enjoy your day.