Recursion question
Blitz3D Forums/Blitz3D Programming/Recursion question
| ||
I'm not sure about the following: when I use a recurive function call, eg: global b test() waitkey() end function test() local a=rand(100) print a b=b+1 if b<2 then test() b=b-1 print a waitkey() end function (b is the recursion depth limiter here) THe question is: when I got a local variable in a function that is called recursively, will always the same A be used (since it's in the same function), or has each "instance" of the recursion its own A variable, that is only affected by the immediate instance? Right now it seems to me the second is true. but I'd like to see this confirmed. |
| ||
Each instance has its own A var. [edit] ...as is demonstrated here: Global count Recursion() Function recursion() count = count + 1 Print "Recursion function called " + count + " times." A = A + 1 Print "A = " + A If count = 100 Then End Recursion() End Function |
| ||
Thanks. |
| ||
@GFK small change to youre code to show something elseRecursion() Function recursion() Global count=0 'Only Acted apon once Local a=0 'Acted apon every recursion/function call count = count + 1 Print "Recursion function called " + count + " times." A = A + 1 Print "A = " + A If count = 100 Then End Recursion() End Function Global in a function is static, and is only initialized once. Locals in a function arent static, and are initalized each call to the function (Only do this when you are really really sure you dont want to access the count (in this case) anywhere else, and in this case is stupid to be used, cos once its set to 100, it stays at 100 and never drops cos we are just "ending", but in a real situation, before the returns would need to count:-1) |
| ||
Global in a function is static In BlitzMax, yes. In Blitz3D (which this thread is presumably about), static vars aren't possible inside a function, so they have to go outside as a Global. That was one thing I was so glad to see added to BlitzMax: functions with static vars could be self-contained and didn't need Globals scattered outside. |
| ||
Woops Errr, Well done Wendel for spoting my deliberate mistake ;) Note to self: Read which Board a Qustion is in (I had wondered why GFK hadnt used Local or strict) |