views:

94

answers:

1

I'm loading a bunch of images into my AS2 flash movie, and I've encountered some strangeness.

Roughly, my code looks like this:

function doTheLoading()
{
    m_imageClips = [];

    for (var i:Number = 0; i < 3; i++) 
    {
        var imageUrl:String = "http://server/" + i + ".jpg";

        var mc :MovieClip = m_mc.createEmptyMovieClip("name"+i, i + 1);

        m_imageClips.push( mc );

        var mcLoader:MovieClipLoader = new MovieClipLoader();
        mcLoader.addListener(this);
        mcLoader.loadClip(imageUrl, mc);
    }

    myDebug("array1: "+m_imageClips);
}


function onLoadComplete(mc:MovieClip)
{
    myDebug("array2: " + m_imageClips );
    myDebug("type: " + typeof(m_imageClips[0]) );

    for (var i:Number = 0; i < m_imageClips.length; i++) 
    {
        if (mc == m_imageClips[i]) 
        {
            /* This line is never reached. */
        }
    }
}

And the output looks something like

array1: mc.0.jpg, mc.1.jpg, mc.2.jpg
array2: ,,
type: movieclip
array2: ,,
type: movieclip
array2: ,,
type: movieclip

So my question is why does my array content seem to change when in the onLoadComplete call? If the array is out of scope, then why can I still see the length of the array and determine the type of the contents?

A: 

The bit of code you posted works fine when I run it, so I think your problem must be somewhere else. Can you post any more of your code?


As an aside, Ross's answer suggests that there's a scope problem, but it's a bit more complicated than that...

It's not quite true to say that m_imageClips is out of scope: if you haven't declared m_imageClips (with a var statement) before you assign it the value of [], then it will be declared automatically.

Many programming languages require variables to be declared before data may be deposited into them; failure to do so would cause an error. ActionScript is not that strict. If we assign a value to a variable that does not exist, the interpreter will create a new variable for us. - (Colin Moock, Actionscript the Definitive Guide)

In this case, it will be declared within the scope of the main timeline, so it will be available to both the doTheLoading() and onLoadComplete() functions. Hence the code runs fine as you've shown it.

This also means that if you do want to use Ross's solution (with a return statement etc), you need to declare m_imageClips to be local to doTheLoading() by using varm_imageClips = []; inside that function. Kind of doubling-up though, since you end up in the same place...

Richard Inglis