This chapter covers
- Writing and using functions in ChucK
- Defining and naming functions
- Function arguments and return types
- Functions that can call themselves
- Using functions for sound and music composition
Now that you’ve had fun building a drum machine using the SndBuf UGen, it’s time to learn how to write and use functions. You’ve already used a number of functions, which we’ve also called methods, ranging from changing the .freq and .gain of oscillators, to using Std.mtof() for converting MIDI note numbers into frequencies, to generating random numbers using Math.random2() and Math.random2f(). All of these are examples of functions.
Often in writing programs you need to do the same types of things multiple times and in multiple places. So far you’ve retyped or copied and pasted blocks of code, possibly changing them just a little. You’ve seen how using ChucK’s built-in Standard and Math library functions help you get lots of work done by calling them with an argument or two. What if you could create and call your own functions? That’s what you’ll learn how to do in this chapter.
Adding functions to your programs will allow you to break up common tasks into individual units. Functions let you make little modules of code that you can use over and over. Modularity helps with reusability and with collaboration with other programmers and artists. It also makes your code more readable.