When you start to have a lot of code, you may notice that your workspace has gotten a lot messier and you want to tidy up a bit. Thankfully, we can use something called a function to do just that. Functions will allow you to group sections of code and name those sections that can then be called later. Look below to see an example:
define :foo do play 50 sleep 1 play 55 sleep 2 end foo sleep 1 2.times do foo end
The code above allows you to name the sequence of code and then run it later. Here we defined a function called :foo! This function tells Sonic Pi to play the note 50, sleep for 1 beat, play note 55, then sleep for 2 beats. So instead of typing all those instructions out, you can call the :foo function and it’ll remember it for the next time!
You can name your function anything you want but it is best to be descriptive.
🌟 Remember, that all functions have to start with a colon. Once you’ve defined it, when you are ready to call the function all you have to do is type its name and it will run!
Another nice thing about functions is that they can be remembered across runs. This means that after you run it once you can delete the function but it can still be called by typing the name. Give it a try by deleting the function in your code! This function can only be used in this buffer and during this session but it can be used as many times as you want.