functions calling self
Blitz3D Forums/Blitz3D Beginners Area/functions calling self
| ||
if i have a function that calls itself, and it calls from a loop, will it continue from its looping position? lopping (3rd tick) -> call self ~ looping (1st tich) -> call self ~ looping(1st tick) will it eventually get back to the 3rd tick loop, or start again? |
| ||
if you have the following.function dosomething() for loop1 = 1 to 3 dosomething() next loop1 then it will never end. Each call will keep calling again and again, never getting to the end of any one function. |
| ||
They're known as recursive functions. You could write a function, for instance, to scan the entire contents of your hard drive - it'd work by scanning each object. If its a file, add the filename to a list. If its a folder, the function can then call itself and read the contents of that folder, checking for more files and sub-folders ad infinitum. To answer the original question - yes, it will resume from the point where it left off. Dynaman's example above will eventually cause a stack overflow error (once he puts an 'End Function' in there, that is). ;) |
| ||
Just to clarify -- if you call a function from a loop, it will NOT continue from its looping position. The new call is a whole new thing. However, once you RETURN from the new call, it will continue from the original point of recursion. This is why it's imperative that when you write a recursive function, there always be a base case to check and return from, in addition to another case which will call itself. (Note that what the base case checks should change through the recursive calls, too.) Here's an example. Watch it perform through the debugger -- you'll see what it's doing. Global count% = 1 Global decimal% = 10 Bits(10) Print "It takes "+count+" bits in binary to represent decimal 10" Function Bits%(x%) If x = 1 Return count Else count = count + 1 x = Bits(x/2) EndIf End Function |
| ||
> Dynaman's example above will eventually cause a stack overflow error (once he puts an 'End Function' in there, that is). ;) Pick, pick, pick |
| ||
justa quick note. When calling recursive functions you end up with whatever is loaded in memory each time the function is called before calling itself. So large object/type declarations etc. should be called after the recursive function call if possible. This will speed up your processing as well as shrink memory usage of the recursive function. ie BAD WAY function FINDSTUFF(Value1) dim HUGEARRAY(10022) if x=y then FINDSTUFF(x) else dootherstuff with HUGEARRAY end if end function ----------------------- GOODWAY ---------------------- function FINDSTUFF(Value1) if x=y then FINDSTUFF(x) else dim HUGEARRAY(10022) dootherstuff with HUGEARRAY end if end function ------------------ Its a simple thing to check after you get the function working. If you dont do it it may cost you heavy fPS for not streamlining. |
| ||
i got it all fine, thanks :) |