Recursive call function

Discussion in 'Programming' started by ashl1, Feb 24, 2008.

  1. #1
    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?
     
    ashl1, Feb 24, 2008 IP
  2. dshuck

    dshuck Peon

    Messages:
    92
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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):
     
    dshuck, Feb 25, 2008 IP
  3. ashl1

    ashl1 Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    ough. thanks. it's great!
     
    ashl1, Feb 25, 2008 IP