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.
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; }