Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Duplicate variable definition

If I have 2 for loops both declaring var i, then the second will produce a warning:

public function twoLoops(){
    for (var i:int = 0; i < 100; i++) {
    }

    for (var i:int = 0; i < 100; i++) { // i is already declared once
    }
}

I understand the reason this happens, it's explained in this answer, but is there a way around it (except for declaring i at the beginning of the method)?

like image 619
Drahcir Avatar asked Dec 31 '25 10:12

Drahcir


2 Answers

It's simple - just don't declare it in the second loop:

public function twoLoops(){
    for (var i:int = 0; i < 100; i++) {
    }

    for (i = 0; i < 100; i++) { // i is already declared once
    }
}

This will work with no error - as your warning tells you, it's already defined, so you can use it again, setting it back to 0 to allow the loop to execute properly.

like image 193
MickMalone1983 Avatar answered Jan 02 '26 01:01

MickMalone1983


If you are so adamant in using the loop the way you are using, consider wrapping up in a function:

public  function twoLoops() {
    for (var  i:int = 0; i < 10; i++) {
    }

    (function(){ 
        for (var i:int = 0; i < 100; i++) { // i is already declared once       
        } 
    })();
}

Though it would not give any warning, I wonder what purpose would it really solve for you.

like image 26
loxxy Avatar answered Jan 02 '26 01:01

loxxy