A Flash Developer Resource Site

Results 1 to 6 of 6

Thread: Declare variables in a "for" loop.

  1. #1
    Member
    Join Date
    May 2009
    Posts
    34

    Declare variables in a "for" loop.

    Hello,

    Does anybody know if it's possible to declare variables in a "for" loop or in a "for each in" statement?

    If it isn't possible, is there any workaround to this? I'm not entirely informed about single variable usability, e.g. having only one "Sound" variable and playing multiple files from only that variable.
    Thanks!

    Example:

    Code:
    var audio:Sound;
    
    for (var i:int=0; i>5; i++) {
         audio[i]=new Sound();
    }
    or
    Code:
    for (var i:int=0; i>5; i++) {
         var audio[i]:Sound=new Sound();
    }

  2. #2
    Ө_ө sleepy mod
    Join Date
    Mar 2003
    Location
    Oregon, USA
    Posts
    2,441
    PHP Code:
    var audio:Array = [];

    for (var 
    i:int=0i>5i++) {
         
    audio[i]=new Sound();


  3. #3
    Member
    Join Date
    May 2009
    Posts
    34
    Thanks a lot sleepy mod!
    However, I still can't get it to work. Please lend me a hand...

    PHP Code:
    var audio:Array=[];
    var 
    urlrequest:URLRequest=new URLRequest("zzz1.mp3");

    for (var 
    i:int=0i>1i++) {
        
    audio[i]=new Sound();
        
    audio[1].load(urlrequest);
        
    audio[i].addEventListener(Event.COMPLETEloadCom);
    }

    function 
    loadCom(event:Event) {
        
    audio[0].play();
        
    trace("hi");


  4. #4
    Ө_ө sleepy mod
    Join Date
    Mar 2003
    Location
    Oregon, USA
    Posts
    2,441
    Try this:

    PHP Code:
    function loadCom(event:Event) { 
        
    Sound(event.target).play(); 
        
    trace("hi"); 

    The array is basically a list of variables all named the same thing (audio[0], audio[1], audio[2]...) so since you're using the same complete event handler for all of them, you need to specify which object you want to deal with when loadCom is called - it's a lot easier to just grab the event.target than trying to figure out which one in the array just finished loading.

  5. #5
    imagination through stupidity
    Join Date
    Apr 2001
    Location
    P3X-3113
    Posts
    1,238
    All variables created within a 'for' loop are scoped within that code block and thus do not exist outside.
    Nothing to see here, move along.

  6. #6
    Member
    Join Date
    May 2009
    Posts
    34
    OK I did some changes in my code and now it works.

    Thanks a lot to both of you!!!
    Last edited by protoemocional; 06-17-2009 at 03:36 AM.

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