Counting with loops - guyjbrown/bleepmanual GitHub Wiki
Counting with loops
Very often, we want to repeat part of a Bleep program a number of times; for example to play a repeating sequence of notes or drum sounds rather than just one. We can do that using a loop. Try this:
use_bpm(100)
use_synth("rolandtb")
for i=1,4 do
play(C4,{duration=0.15})
sleep(0.25)
end
The statements between the for and end words are repeated a number of times. How many times? That is controlled by the value of a loop control variable, which is this case is called i (it could be any name). Starting from its initial value (which is 1 in this example), each time around the loop we add one to the value of i and stop after we have done the last value specified. In this case, i counts through 1, 2, 3 and 4 in sequence. That means that the play and sleep commands inside the loop (called the loop body) get repeated 4 times.
We can explain what the for loop is doing with a flow diagram like this:
flowchart TD
A[Start] --> B(Initialize counter variable)
B --> C{Check end<br>condition is true?}
C --> |No| E[End]
C --> |Yes| D(execute statements)
D --> F(Update counter variable)
F --> C
🚀 Experiment with different start and end values for i in the loop. If you use really big values you might cause Bleep to crash, but that's fine! Just reload the page in your web browser. You can't break anything.
Using the loop control variable inside the loop
We can use the loop control variable inside the loop to make a sequence of changes. Try this:
use_bpm(100)
use_synth("fmbell")
for note=60,72 do
play(note,{duration=0.2,level=0.8})
sleep(0.25)
end
This should play a sequence of notes covering one octave (it's actually a chromatic scale). Loops can count downwards too. Instead of adding 1 to the loop control variable each time around the loop, we could subtract 1 to make a descending scale:
use_bpm(100)
use_synth("fmbell")
for note=72,60,-1 do
play(note,{duration=0.2,level=0.8})
sleep(0.25)
end
We can use a loop to control other parameters too. Here we are counting values from 500, 600, 700 ... 1500 and using this to control the cutoff of a filter:
use_bpm(100)
use_synth("rolandtb")
for c=500,1500,100 do
play(D3,{duration=0.15,cutoff=c})
sleep(0.25)
end
:rocket: Now experiment! Using a for loop to repeat statements in your program is a very powerful thing. You can use it to make sequences of notes, change parameters over time, or sleep for different times. Remember, big values in the loop might cause Bleep to fall over. Just reload the web page!
Next: Making decisions