Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial67 Looping Through Arrays
In the following example, an array is used to store which notes are
currently being played in the track. A loop is used to remove notes as
NoteOff
events are captured. Like the larger example from
before, this gets into a function—HandleMIDI()
—to provide
context for what is happening within the loop itself and the example is
a fairly common task when working in Scripter. The actual loop is in
lines 10–16:
var activeNotes = [];
function HandleMIDI(event) {
if ( event instanceof NoteOn ) {
.push(event);
activeNotes
else if ( event instanceof NoteOff ) {
} var length = activeNotes.length;
for ( var thisNote = 0; thisNote < length; thisNote++ ) {
var note = activeNotes[thisNote];
if ( note.pitch == event.pitch ) {
.splice( thisNote, 1 );
activeNotesbreak;
}
}
}
Trace( activeNotes.length );
}
In the above example:
Line 1: An array is declared which will store the events. This is created as soon as the "Run Script" button is clicked.
Line 3: Scripter executes the
HandleMIDI()
function whenever a new event is encountered.Line 5–17: An
if...else if
statement is used to test what kind of event is being passed into theHandleMIDI()
function.Lines 5-6: If the event is a
NoteOn
event, then add it to theactiveNotes
array.Line 8: If the event is a
NoteOff
event, then the following happens:Line 9: The length of the
activeNotes
array is captured in thelength
variable.Line 10: The
for
statement is declared.var thisNote = 0
declares the loop’s variable. This value will be used as the index to get notes from theactiveNotes
array. Remember that array indexes begin with 0 and increment by 1 until the last item in the array, which has an index of length - 1.thisNote < activeNotes.length
is the condition which is tested. When the index is less than the length of the array, then the code block is executed. When the index equals the length of the array, the loop is immediately stopped and the code block is not executed.thisNote++
will add 1 to thethisNote
value after the code block has been executed. Any number can be added to the value for different kinds of increments. For example, to look at every other note in the array,thisNote += 2
would be used.
Line 11: The current value of
thisNote
is used as an index in theactiveNotes
array.Lines 12–14: The pitch value for
thisNote
is compared to the event. If the patches match, then remove the note fromactiveNotes
and stop the loop.