PDA

View Full Version : Getting variables value from inside function



Nocturn
September 20th, 2003, 05:09 PM
I'm pretty new to AS, I understand that whatever variables you have inside a function will be discarded once the function finishes?

I need the value of a variable that's inside a function, I've tried declaring it outside the function, and also give it an initial value, but it seems that when the function finishes the variable goes back to it's original value.

lostinbeta
September 20th, 2003, 05:20 PM
Don't use "var" before declaring the variable.

For Example..
function myFunction() {
myVar = 5;
}
myFunction();
trace(myVar);
//returns 5

and
myVar = 2;
function myFunction() {
myVar = 5;
}
trace(myVar);
myFunction();
trace(myVar);
//returns 2 then 5


There is are tutorials on the variable scope and var declaration here at kirupa.com if you want to check them out.

Jack_Knife
September 20th, 2003, 06:07 PM
You can use the return function inside the function if you only want one variable to be changed/returned. eg.

function myFunc() {
myVar = 2+2;
return myVar;
}
trace(myFunc());

Nocturn
September 20th, 2003, 06:08 PM
Ok, thanks for that lostinbeta, but this doesn't seem to work with this variable I'm using:
count = imagesTag.childNodes.length;

This is the script from Senoculars site, the portfolio one. I need to know the number of nodes (images) that have been loaded.
If I do a trace(count) outside this function it returns undefined.

Nocturn
September 20th, 2003, 06:12 PM
Well, I don't know how to use that in this case because the function is defined like this:

portfolio.onLoad = function(){
imagesTag = this.firstChild;
count = imagesTag.childNodes.length;

etc etc

lostinbeta
September 20th, 2003, 06:36 PM
Well that is because your function is actually an event handler.

In this case the handler is onLoad.

If you run the trace(count) right after the onLoad it won't work, because in fact the information you are loading in is not yet fully loaded. The onLoad handler waits for all the information to be fully loaded before the actions are triggered, which is what you need to do.