I have a problem with recursive function in CFC and in <cfscript> <cfscript> function fun(n){ Â Â Â Â if (n lt 3){ Â Â Â Â Â Â Â Â for (i=0; i lt 2; i=i+1){ Â Â Â Â Â Â Â Â Â Â Â Â writeOutput(n&" - "&i&" - "&j&"<br />"); Â Â Â Â Â Â Â Â Â Â Â Â j = j+1; Â Â Â Â Â Â Â Â Â Â Â Â fun(n+1); Â Â Â Â Â Â Â Â } Â Â Â Â } } j = 1; fun(1); </cfscript> Its show only: 1 - 0 - 1 2 - 0 - 2 2 - 1 - 3 But i want to see: 1-0-1 2-0-2 2-1-3 1-1-4 2-0-5 2-1-6 Why recursive not return to level1 and call fun(2) when j=4?
This is because you are not var scoping your variables and causing thread collisions. If you are going to use functions you *MUST* use var scoping. If you are not familiar with this, please read my blog entry that gives an example of why this occurs. In fact it is even dealing with var scoping "i" in a loop so it is quite relavent. http://daveshuck.instantspot.com/bl...-Var-scope-your-loop-index-in-ColdFusion-CFCs Now that you have read that (you have right?), here is your solution: <cfscript> function fun(n){ var i = ""; if (n lt 3){ for (i=0; i lt 2; i=i+1){ writeOutput(n&" - "&i&" - "&j&"<br />"); j = j+1; fun(n+1); } } } j = 1; fun(1); </cfscript> Code (markup):