Tutorial: How to write games part 2

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

Using array variables

Each number (or text string) that is stored in an array is called an "array element". Each element behaves like a regular variable. That is, we can read or write to it, use it in expressions, as function parameters or whatever.
We tell the computer which element we want to access by putting the number in brackets after the array variable name. So in the previous examples, n(2) accesses the seond element of the array.

Here's some more examples of using array elements.

dim name$(3), numbers(4)
name$(1) = "Tom"
name$(2) = "Dick"
name$(3) = "Harry"
numbers(1) = 3
numbers(2) = numbers(1)
numbers(3) = numbers(1) + numbers(2) * 2
numbers(4) = sqrt (numbers (3))

As you can see, we are using them just like normal variables.

The Array Index

The number inside the brackets is called the "array index".
This is the number used to 'lookup' the variable in the array. You can think of this like a mailbox number. It tells the postman where the letter is supposed to go.
So for an instruction like:

numbers(3) = 5

We're delivering the number 5 to mailbox number 3.
We could then look inside mailbox number 3 like this:

print numbers(3)

And we would find the number 5 which we just delivered there.
Of course if we used a different array index like 2:

print numbers(2)

We wouldn't find our number 5! We've looked in the wrong mailbox.
(We would infact find a number 0 there, because that is the default for integer variables if we haven't changed them to anything else yet.)

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