randyHurd
randyHurd

Reputation: 64

What does a return statement 'RETURN TO'?

I have an issue that is bound to be very basic. I understand functions, parameters, variables etc... I can even write a return statement.

function returnFunc(myVar:int):int{
return (myVar * 2_);
}

But every lesson or tutorial I see assumes knowledge I do not have. WHERE am I returning this var TO?

Can I create a var myVar in a function, have that myVar passed to another function and returned to the logical order with myVar updated? Or what?

Upvotes: 0

Views: 77

Answers (2)

randyHurd
randyHurd

Reputation: 64

OK. I figured this out finally. There are so many examples that forget to include how the function is called.

For those interested. Here is an example.

function myFunction1()
{
var funVar:int  = 5;
funVar = function2(funVar);// this is where the var gets changed
trace(funVar);
}

function myFunction2(passedVar:int):int
{
return passedVar * 2;
}

Upvotes: 1

user2655904
user2655904

Reputation:

Can I create a var myVar in a function, have that myVar passed to another function and returned to the logical order with myVar updated? Or what?

Yes, exactly. And more.

var i:int = returnFunc(2); //i will hold the value of of the return, so in your case 4.

you could also do something like this

var i:int = returnFunc(returnFunc(2));

so, first the innermost function gets called, and the value it returns is 4. This is passed to the outermost function, and it will return 8.

You can also use return statements to stop functions from executing further.

private function doStuff(i:int):void{
    if(i < 0){
       return;
    }

    ... do stuff
}

or for a non-void function

private function createSprite(type:String):Sprite{
     if(type == "Square"){
         var s:Sprite = new Sprite();
         ...etc
         return s;
     }
     else{
         return null;
     }
}

So, when the function gets called, and parameter i has a value that is below 0, the function will stop and you would never get to the "do stuff" part.

Wikipedia also has some reading material for you. As you said, the return functionality is one of the basics in programming. It'll help you a lot.

To sum it up in one sentence, a return statement stops the execution of the function and returns a value to the object that called it.

Upvotes: 4

Related Questions