02.02.2013 Views

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Flash</strong> <strong>MX</strong> <strong>2004</strong> <strong>Games</strong><br />

1 n = 25;<br />

2 i = 10;<br />

3 <strong>to</strong>tal = 1;<br />

4<br />

5 trace("Sum = " + sumUpTo(i));<br />

6 trace("n = " + n);<br />

7 trace("<strong>to</strong>tal = " + <strong>to</strong>tal);<br />

8<br />

9 function sumUpTo(n:Number):Number{<br />

10 var <strong>to</strong>tal:Number = 0;<br />

11<br />

12 while (n>0){<br />

13 <strong>to</strong>tal += n;<br />

14 n--;<br />

15 }<br />

16<br />

17 return <strong>to</strong>tal;<br />

18 }<br />

Listing 11.5 ‘Examples/Chapter11/debug07.fla’<br />

Again we create some variables in the old way of just assigning them values. The new function<br />

‘sumUpTo’ is passed a parameter, in this case the contents of the variable i. The function declaration<br />

shows that this is supposed <strong>to</strong> be a number. If instead we pass a string then we get an error message.<br />

The function is expected <strong>to</strong> return a number. Within the function we declare a number type<br />

variable called ‘<strong>to</strong>tal’, which is not the same variable as created in line 3. The function decrements<br />

the variable passed in as the parameter n, but this has no effect on the variable i because it is a<br />

copy. Any attempt <strong>to</strong> manipulate it has no effect on the original. The end of the function returns<br />

the value of the local variable ‘<strong>to</strong>tal’. Having returned from the function the original variables<br />

assigned in lines 1 <strong>to</strong> 3 have been unaffected; the trace statements in lines 5 <strong>to</strong> 7 show this <strong>to</strong> be<br />

the case.<br />

Variable scope<br />

‘Examples\Chapter11\debug08.fla’ illustrates another extremely common problem.<br />

In this simple project we have a dynamic text box tracking the variable ‘count’ and a movie clip<br />

with the instance name ‘counter’. The ‘counter’ clip has the following clip events.<br />

1 onClipEvent(load){<br />

2 count = 0;<br />

3 }<br />

4<br />

156

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!