Tutorial: How to write games part 2

Go to page << 1 2 3 4 5 6 7 8 9 10 11 >>


An array is a special kind of variable. You remember that a variable is used to store a number or a string, like in this (fairly meaningless) program:

dim count, temperature#
dim model$
count = 5
temperature# = 33.44
model$ = "Plastico 12B"

However, instead of just storing 1 number or string, an array can store many numbers or strings.

To illustrate, let's suppose we wanted to store three numbers.
We could simply use 3 different variables:

dim n1, n2, n3
n1 = 4
n2 = 3
n3 = n1 + n2

But we could also store all three numbers in a single array variable, like this:

dim n(3)
n(1) = 4
n(2) = 3
n(3) = n(1) + n(2)

This looks pretty similar to the first program. The biggest difference being that there are brackets around the numbers.
The dim n(3) statement tells the computer that we want an array of 3 elements called n. This is the array variable name, and follows the same rules as normal variables (for example, we know that the array stores integers because there is no special symbol after the n. Had we called it n$ as in dim n$(3), we would have been given an array of three text strings).

So is this better?
Admittedly it's slightly longer and doesn't do anything particularly better. But bear with me, because there are things we will learn to do with arrays that we can't do with regular variables.
One situation is if we want to store a large number of variables, say 1000. Obviously it would take us a long time to write out code to "dim" 1000 different variables.

dim n1, n2, n3, n4, n5, n6, n7, n8, n9, n10

But with an array we just do this:

dim n(1000)

And there are other advantages which we will see soon.

Go to page << 1 2 3 4 5 6 7 8 9 10 11 >>