muudless
muudless

Reputation: 7532

as3 How can a function use variable from another function?

Obviously I'm new to as3...Can someone please explain to me how I can use the variable from one function in another function?

For example:

function init():void {
 var test:Number = 1;
}

init();

trace(test);

I get an error:

1120: Access of undefined property test.

Upvotes: 0

Views: 3374

Answers (1)

Marty
Marty

Reputation: 39458

Either define the variable outside of the function:

var test:Number = 0;

function init():void
{
    test = 1;
}

init();

trace(test); //output: 1

Or return the value from the init() function like this:

function init():Number
{
    var test:Number = 1;
    return test;
}

trace(init()); //output: 1

Note:

Normally you'd just do:

function init():Number
{
    return 1;
}

But I did the above for the sake of explanation.

Upvotes: 1

Related Questions