Passing arrays to functions

Array are just like any other variables in that they can be passed into functions as parameters. Here's a small example program that shows how it is done.

score as integer [ 3 ]

score [ 1 ] = 10 score [ 2 ] = 20 score [ 3 ] = 30
do UpdateScore ( score )
for i = 1 to 3 print ( score [ i ] ) next i
sync ( ) loop
function UpdateScore ( values as integer [ ] ) for i = 1 to values.length values [ i ] = values [ i ] + 2 next i endfunction

Here's how it works.

If you run this program you will see 0, 0 and 0 displayed on screen instead of the scores continually getting larger and larger as you might expect. The reason for this is that by default AppGameKit takes parameters being passed into functions and copies their data, resulting in the parameter being a complete copy of the data passed in. The original data remains untouched by the function.

If you want to modify the data being passed into the function then the parameter needs to be declared slightly differently - use the ref keyword after the name of the variable and before the as keyword. Here's the same program, but this time the type is passed in as reference, resulting in its data being modified directly by the function.

score as integer [ 3 ]

score [ 1 ] = 10 score [ 2 ] = 20 score [ 3 ] = 30
do UpdateScore ( score )
for i = 1 to 3 print ( score [ i ] ) next i
sync ( ) loop
function UpdateScore ( values ref as integer [ ] ) for i = 1 to values.length values [ i ] = values [ i ] + 1 next i endfunction

When you run this program all 3 scores contained within the array will continually increment because the parameter has been declared using ref, therefore a copy is not made and the data being passed into the function will be directly modified by the function.

To pass multidimensional arrays to functions use additional square brackets in the function declaration, as shown in this program.

score as integer [ 2, 3 ]

score [ 1, 1 ] = 10 score [ 1, 2 ] = 20 score [ 1, 3 ] = 30
score [ 2, 1 ] = 100 score [ 2, 2 ] = 200 score [ 2, 3 ] = 300
do UpdateScore ( score )
for i = 1 to score.length for j = 1 to score [ i ].length print ( score [ i, j ] ) next j
print ( "" ) next i
sync ( ) loop
function UpdateScore ( values ref as integer [ ] [ ] ) for i = 1 to values.length for j = 1 to values [ i ].length values [ i, j ] = values [ i, j ] + 1 next j next i endfunction

The UpdateScore function has two sets of brackets for the parameter, meaning it expects a 2 dimensional array to be passed into it. If three sets of brackets were to be used then a 3 dimensional array would need to be passed into the function.