| Exercise 6.1 - Code Blocks | 1 | 2 | 3 |
So far, we have written short code fragments to define specific musical events and properties. In this tutorial, you will learn how to write blocks of code to perform a series of tasks, to capture more complex functionality. These code blocks (or subroutines) can either be placed in a cell directly and triggered when the cell is played, or associated with a pattern effect and used whenever the effect is used in the pattern.
In Manhattan, code blocks also allow us to push (write) data to other parts of the pattern, whereas previously we have only pulled (read) data to write to the current cell. For this we will learn about the assignment operator, =.
To create a code block in a cell:
[+2].pitch = .pitch + 7
| Exercise 6.2 - Code Order | 1 | 2 | 3 |
Understand the order of execution:
.pitch = rnd(C-5, B-5)
.pitch = rnd(C-5, B-5)
[+2].pitch = .pitch + 4
[+2].pitch = .pitch + 4
.pitch = rnd(C-5, B-5)
You can copy this cell (including its code) and paste it elsewhere in the pattern to perform the same task in other place - but we can also simply 'call' upon another cell's code when we need it...
| Exercise 6.3 - Calling Code | 1 | 2 | 3 |
While copy-and-pasting cells allows us to reuse the code that we've written (which get copied as part of the cells), the pattern can get messy and unmanageable as the amount of code grows. Moreover, imagine if we later want to alter the code, but then have to update all the different copies strewn across the music.
Instead, we need a mechanism to be able to write code once in one place, and then reuse it whenever and wherever we need. This is the principle of functions, explored in the next tutorial, but Manhattan also offers a simple mechanism for one to simply 'call' the code of another other cell...
Executing (or calling) code from another cell:
@Conversation.run()
The .run() function is an instruction to take the code from the referenced cell (i.e. @Conversation) and run it in the current cell. At the moment, however, there is no such cell.
' A little John Williams magic...
[+1].pitch = .pitch + 2 ' up a major 2nd
[+2].pitch = [+1].pitch - 4 ' down a major 3rd
[+3].pitch = [+2].pitch - 12 ' down an octave
[+4].pitch = [+3].pitch + 7 ' up a perfect 5th
The .run() mechanisms is extremely powerful, and allows you to collect fragments of code together, name them, and call upon them wherever and wherever you need. It can even be useful to set aside a muted channel to host arrays and the code blocks you frequently use, and call on them by name in the rest of your pattern.
In the next tutorial, we'll explore functions, another mechanism for writing code that can be reused, but also adapted for different situations.