Groups | Blog | Home
all groups > flash actionscript > march 2006 >

flash actionscript : Variable not working outside of a funtion...



DIY_Lobotomy
3/26/2006 6:32:59 PM
Okay, below is a small segment of a large bit of code that I have written...

You'll see two "trace" statements. The one INSIDE the function returns "5"
(which is correct). The one OUTSIDE the function returns "undefined". I need
to use this variable elsewhere, but it seems to only work inside the
function!...

If someone can troubleshoot this for me, it would be greatly appreciated.
Thanks!!!....

--Hoffman

P.S. - I am using Flash 8



// :: POPULATES THE TEXT FIELDS OF THE PLAYER :: \\
function populateText() {
var songList:Array = songXML.firstChild.childNodes;
var songTotal:Number = songList.length;
trace(songTotal);
artist_txt.text = songXML.firstChild.childNodes[songNum].attributes.artist;
title_txt.text = songXML.firstChild.childNodes[songNum].attributes.title;
album_txt.text = songXML.firstChild.childNodes[songNum].attributes.album;
label_txt.text = songXML.firstChild.childNodes[songNum].attributes.label;
date_txt.text = songXML.firstChild.childNodes[songNum].attributes.date;
venue_txt.text = songXML.firstChild.childNodes[songNum].attributes.venue;
var songLoc:String = songXML.firstChild.childNodes[songNum].attributes.url;
}

trace(songTotal);
TimSymons
3/26/2006 6:39:59 PM
That is the difference between local and global variables.

You defined the variable inside the function:

var songTotal:Number = songList.length;

If you defined it outside the function the you could use it in both places.
Kind of like this.

var songList:Array = new Array();
var songTotal:Number;

function populateText() {
...rest of your code here without the 2 variable declarations
}

Tim
DIY_Lobotomy
3/26/2006 6:45:59 PM
Cool, thanks - that worked. But what do you mean by this?:
you should define the variables and function within the same movieclip
...because I don't have EITHER of those pieces of code in a MC. All my code
is on the root timeline.

TimSymons
3/27/2006 3:27:33 AM
The _root is like a movieclip. When you place other movieclips on the timeline
they each have their own timelines and you can place actionscript in them as
well. If you defined the variables in a movieclip (lets name it test_mc) and
then placed this test_mc on the _root timeline then you would have to reference
them from your function on the _root timeline like this:

test_mc.songList

test_mc.songTotal

Hope that makes a little better sense from what I wrote before.

Tim
AddThis Social Bookmark Button