Previous | Next

Making your own macros with parameters

In the following lessons we will expand on the drawing application by adding new functionalities. However, before we do so, we will restructure the code a little bit to make it more readable:
//Right-click to download this code

import "tagtiles.esp"

main = (
  handleYellow | handleBlue | handleRed | handleGreen
)

handleYellow = (
  handleColor isYellowBlock yellow
)

handleBlue = (
  handleColor isBlueBlock blue
)


handleRed = (
  handleColor isRedBlock red
)


handleGreen = (
  handleColor isGreenBlock green
)

handleColor obj clr =  (
 loop (
    await (tagEvent down obj);
    drawShape (Cell lastTagCoord) clr
  )
)
Notice that the application still does the same, but it is written down in fewer lines. To achieve this, we added the handleColor macro. This macro isolates the combination of macros that wait for a colored block and then draw that color on the TagTiles board.

The macro handleColor is the first macro we have made that uses parameters: namely obj and clr. We use the macro for instance in handleYellow, which is defined as:
handleColor isYellowObject yellow

Whenever you use the macro handleYellow, the compiler looks up its definition and sees that you defined it using handleColor. Therefore, it fills out the definition of handleColor, but replaces yellowObject for obj and yellow for clr. Notice that that gives us exactly the definition of handleYellow that you created in the previous chapter.

Having a macro such as handleColor is very useful, because defining handleYellow, handleBlue, handleGreen and handleRed, is just a matter of providing handleColor with the right parameters for obj and clr, which is exactly what we did in the example above.

Exercise

  • Rewrite handleBlue manually, by copying the definition of handleColor, while replacing obj with isBlueObject and clr with blue.
  • Is there a difference with the definition of handleBlue from the previous chapter?


Previous | Next
Serious Toys logo -  tangible inspiration without limitation