ForumsProgramming ForumFunctions

6 3466
clipman3
offline
clipman3
5 posts
Nomad

I have had a really hard time with functions. I have flash mx 2004(AS2), and whenever i try to make a function it doesnt work for some reason. I have been trying to learn for a long time now, and i cant seem to get it down, so if someone could help me with a very broken down explanation, that would be awesome. thanks in advance to anyone who helps me out.

  • 6 Replies
PixelSmash
offline
PixelSmash
566 posts
Nomad

Very broken down, a function is a block of code - much like anything else. However, it's easier to do a function call rather than retype the lines inside that function over and over.
(note: the code I use is in AS3, but it's the idea that counts!)

So, let's say we have a function here:

function doSomething():void
{
var a:Number = 15;
a = a * 15;
...etc etc
}

you could in your code write those lines over and over again. But, it's a lot easier to call the function with 'doSomething()'
Also, if you use the right naming, you can write a function and sort of forget what it does, as the name already implies what it does - making your code a lot more readable and shorter.

Other things you can do with functions is pass arguments, like so:

function multiply(a:Number, b:Number):void
{
trace( a* b);
}

you can call this by typing multiply(2,5), which should trace 10 (2*5=10).

The final thing for now is return values. You can call a function and have it return a certain value, like this:

function returnFive():Number
{
return 5;
}

which you can call with returnFive(), but you can use it as a value of sorts: var a:Number = returnFive(); (which gives a the value of 5)

Combined, you can do something like this:

function multiply(a:Number, b:Number):Number
{
return a*b;
}

Hope this helps you a little!

clipman3
offline
clipman3
5 posts
Nomad

thanks a lot, it makes a little more sense now. but how do i apply functions to work when something happens?

Darkroot
offline
Darkroot
2,763 posts
Peasant

Functions are like little black boxes that do something with some input. You just call them when you need something done and feed them input.

clipman3
offline
clipman3
5 posts
Nomad

[quote]Functions are like little black boxes that do something with some input. You just call them when you need something done and feed them input.

thanks, but i mean how can i get the functions to work on demand?

Darkroot
offline
Darkroot
2,763 posts
Peasant

You have to call them here is an example;

function showMsg(msg:String) {
trace(msg);

Here above we have function "showMsg" that when called use the string and traces it.

showMsg("goodbye"

Here we called it and use the string goodbye it should trace goodbye in the output panel.

clipman3
offline
clipman3
5 posts
Nomad

oh, ok, that makes more sense. thanks a lot darkroot and pixelsmash. i really appreciate it!

Showing 1-6 of 6