Tutorial: How to write games part 2

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

Other ways to specify the array index

We put a 3 in the brackets to specify array index 3.
But what if we had used something like 1+1+1 instead?

dim numbers(4)
numbers(1+1+1) = 5
print numbers(3)

Would this compile?
Would it have the same effect?

The answer is: yes, it does exactly the same thing. Type it in an run it, and you'll see that it does indeed print a 5 on the screen.

The reason this works is that the array index doesn't have to be just a single number. It will also accept any expression that sums up to a single number.

So we could have used 2 + 1 or 7 - 4 or sqrt (9) all to access mailbox number 3.
The computer is quite happy to calculate the result of this sum and go to the appropriate "mailbox".
(Unlike the postal service who turn their nose up at any address that requires long division... Don't ask...)

Using a variable for the array index

Here's another way to access the 3rd element (mailbox) of the numbers array:

dim numbers(4), i
i = 3
numbers(i) = 5
print numbers(3)

This is actually a very powerful technique!

What we've done is declared a variable i, and then stored the number 3 in it.
Then we've used i as the array index!
Remember that we can use any expression we want to calculate the array index number, and that includes other variables like i.
Again the computer calculates the expression, and sees that it comes out as 3. So off to index 3 it goes and stores in the number 5.

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