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 ) {
activeNotes.push(event);
} 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 ) {
activeNotes.splice( thisNote, 1 );
break;
}
}
}
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 ifstatement is used to test what kind of event is being passed into theHandleMIDI()function.Lines 5-6: If the event is a
NoteOnevent, then add it to theactiveNotesarray.Line 8: If the event is a
NoteOffevent, then the following happens:Line 9: The length of the
activeNotesarray is captured in thelengthvariable.Line 10: The
forstatement is declared.var thisNote = 0declares the loop’s variable. This value will be used as the index to get notes from theactiveNotesarray. 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.lengthis 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 thethisNotevalue 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 += 2would be used.
Line 11: The current value of
thisNoteis used as an index in theactiveNotesarray.Lines 12–14: The pitch value for
thisNoteis compared to the event. If the patches match, then remove the note fromactiveNotesand stop the loop.