Arrays

Arrays is a type of collection in max. One important difference between arrays in C/C++ and arrays in max is that max arrays can have elements of different datatypes within the same array. This is very diffrent from C/C++ in that all elements of an array must be exactly the same type.

Think of arrays as simply an indexed list, where each list item can be anything.

Furthermore arrays are indexed starting 1 and not 0 like C/C++.

Array declaration:

To declare an array use the following notation:

emptyArray = #()

anotherArray = #(2,4,6,8)

thirdArray=#(2,4,6, "hello", "goodbye", red)

Array access

To access any element of an array, use arrayName[index]. For example, the following prints the first element of the array anotherArray:

anotherArray = #(2,4,6,8)
print anotherArray[1]

Function calls and arrays

Like C/C++, arrays passed to functions are pass by reference. That is if you pass an array to a function and the function changes the array, your original array will be modified.

fn checkArrayRef array=(
   for i=1 to array.count do(
       array[i]=array[i]+10
   )
)

anotherArray = #(2,4,6,8)

for i=1 to 4 do(
    print anotherArray[i]
)

checkArrayRef anotherArray

for i=1 to 4 do(
    print anotherArray[i]
)

Mapped functions

A function may be preceded by the keyword mapped. If this keyword is present, it will allow you to apply the function through every element of a collection.

For example consider the following function:

mapped function mprint p = (
   print p
)
mapped function changeToRed co =(
   co.red=255
   co.blue=0
   co.green=0
)

a = #(red,green,blue,yellow)
mprint a
changeToRed a
mprint a

In the above example, the functions are both mapped. Thus, when I call it using an array, it will automatically call the function using every item in the array.

For loops and arrays

When working with a collection like an array, the for loop can go through the entire collection of objects.

For example:

myArray=#("alpha","beta","gamma")
for theString in myArray do(
  print theString
)

You can also use a for loop to collect things into an array using the collect statement. The result of the expression in the loop is added to the array:

myArray=#()
for i = 1 to 10 collect (
    i*2
)