An Array is a Collection with a finite maximum size, determined at declaration time. It is the programmer's responsibility to maintain a meaningful order, and to remember the meaning of the data. Data in an Array is called "elements," each of which is assigned a specific "index number." Index numbers begin at 0. Any mix of Objects can be stored in an Array, including an Array.
This example declares an Array, adds some elements, then prints them out.
(
var tA = Array.new( 2 ); // "tA" stands for "testArray"
tA = tA.add( 5 );
tA = tA.add( 3 );
tA = tA.add( 17 );
tA.postln;
nil;
)
Notice that Array is a Class, and it must be instantiated before use. Here, the variable
tA
is assigned an Array with enough space for two objects. Notice that the elements are printed out in the order that you add them to the Array. They are not sorted or shuffled (unless you send a message like
scramble
). But why did I write
tA = tA.add( 17 );
instead of
tA.add( 17 );
? Shouldn't the second method be sufficient for adding an Object to an Array, thereby making the re-assignment unnecessary? It does, but let's see what happens when we take it away:
(
var tA = Array.new( 2 ); // "tA" stands for "testArray"
tA.add( 5 );
tA.add( 3 );
tA.add( 17 );
tA.postln;
nil;
)
The
17
is missing - it doesn't get added into the Array! This is because the Array was only declared with two slots, and you can't add three Objects into two slots. So why did this work the first time?
SuperCollider was programmed to help us fit additional items into an Array. If an Array has reached its capacity,
SuperCollider will automatically make a new, larger Array for us, and returns that from the
add
method. Therefore, any time you add an element to an Array, you should always re-assign the result, so that you don't have to worry about whether you exceeded the Array's capacity.