A Flash Developer Resource Site

Results 1 to 4 of 4

Thread: Break embedded loops simultaneously

  1. #1
    Bacon-wrapped closures Nialsh's Avatar
    Join Date
    Dec 2003
    Location
    Houston!
    Posts
    338

    Break embedded loops simultaneously

    Does anyone know how to break out of embedded for loops with the same command from the inner loop?
    example:
    Code:
    for(i = 0;i < 10;i ++){
    	for(n = 0;n < 10;n ++){
    		if(myFunction(i,n)){
    			//do something
    			//break out of both loops
    		}
    	}
    }
    I know I could have an extra conditional in the outer loop that checks a variable that gets set by the "if", but that's a lot of extra processing.
    Thanks for any help.

  2. #2
    Senior Member jbum's Avatar
    Join Date
    Feb 2004
    Location
    Los Angeles
    Posts
    2,920
    Unfortunately, there's no 'goto' command in Flash, although it would come in handy in this case - this is what happens when language designers get overly politically correct.

    Here's a few things you could do:

    1. Put the whole thing in a function and use return. Costs a little extra for the function call, but possibly not as much as adding a condition to the outer loop.

    code:

    myLoopy = function()
    {
    for(i = 0;i < 10;i ++) {
    for(n = 0;n < 10;n ++) {
    if(myFunction(i,n)) {
    //do something
    //break out of both loops
    return;
    }
    }
    }
    }




    2. Use a single loop. Unfortunately, more processor intensive than adding a condition on the outer loop.

    code:

    for(x = 0;x < 100; x++){
    if (myFunction(Math.floor(x/10),x%10)) {
    //do something
    //break out of both loops
    break;
    }
    }



    3. Your original suggestion. Probably not that painful, since the bulk of your CPU time happens in the inner loop. This is the choice I'd probably use myself.

    code:

    over = false;
    for (i = 0; i < 10 && !over; i++) {
    for (n = 0; n < 10; n++) {
    if (myFunction(i,n)) {
    //do something
    //break out of both loops
    over = true;
    break;
    }
    }
    }

    Last edited by jbum; 08-06-2004 at 03:22 PM.

  3. #3
    Bacon-wrapped closures Nialsh's Avatar
    Join Date
    Dec 2003
    Location
    Houston!
    Posts
    338
    Thanks! I didn't think of putting it in a funciton, but that should work well since I use it twice anyway.

  4. #4
    Junior Member
    Join Date
    Dec 2008
    Posts
    1
    consider also changing the outer loop's variable to something that will break it.
    i.e.
    Code:
    for ( i=0; i<40; i++ ) {
        for ( k=0; k<100; k++ ) {
          if (somecondition) {
            i = 40;
            break;
          }
        }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center