Writing the same lingo commands repetitively, is cumbersome and error-prone. Functions provide a powerful way of abstracting what is important of the code and naming it into a new construct, called a function (or a handler). The file contains two dots, a red and a blue that are placed on stage. There are also a couple of buttons that move the dots three steps ahead while leaving their marks on the stage (creating the effect of dot-dot-dot). Their script is as follows: on mouseUpNote that the trails property allows a sprite to leave a mark on the stage every time it moves. This script can be used to create lines out of a single pixel, for example. Of course we can use the repeat statement to avoid writing the three repeated statements three times, as we have done with the blue dots button: on mouseUpIf, down the road we wanted to reuse this dot-dot-dot behavior, we would have to copy the code and paste it inside another handler. A function would allow us to abstract this behavior and package it inside our own handler : on ThreeDotsNow our mouseup code can be simplified to be: on mouseUp ThreeDots end It is important to understand what is going on here: When the user clicks the mouse, Lingo sees that it needs to execute ThreeDots. The control of execution is transferred to ThreeDots then, the function we have declared ourselves (important: in a Movie Script). Lingo executes the script and then returns back to the mouseUp handler. As you noticed, this is good but not good enough: It always prints three dots. What if we wanted to print 5 or 10? Should we create another handler FiveDots or TenDots? That goes against the idea of having a function in the first place. What we can do is create a function that takes an argument instead: on dots howMany -- shows how to create a function/handler with a parameter -- howMany: number of red dots to draw sprite(1).trails = 1 repeat with num = 1 to howMany sprite(1).locH = sprite(1).locH + 10 put sprite(1).locH updateStage end repeat end Notice that the parameter howmany will eliminate the need for ThreeDots, FiveDots or TenDots. These function are simply calls to the new function dots with arguments 3, 5, 10. We can take this example one step further. What id we wanted to have a script that will create red dots or blue dots? It is better to abstract not only the number of dots we are drawing on the stage, but also their color. That is accomplished by the function colorDots: on colorDots howMany, whichColor -- shows how to create a function/handler with two parameters Can you create functions that draw a square of dots?
|
|
Maintained By: Takis Metaxas
|