Using arrays rather than several similar variables saves you time and energy. It also helps you write code that can be re-used.
Arrays in FreeBASIC Tutorial I
An array is a variable that has multiple slots. If you are using several related variables, you may want to use an array instead. For example, let's say your game has 5 players. Your game has to keep track of the scores of each player. You could make 5 separate variables :
Dim playerScore1 As Integer
Dim playerScore2 As Integer
Dim playerScore3 As Integer
Dim playerScore4 As Integer
Dim playerScore5 As Integer
Or, you could create one array :
Dim playerScores(1 To 5) As Integer
This creates an array with 5 slots numbered 1 to 5. If we were to graph how the array structure looks, it would look much like this :
playerScores | |||||
---|---|---|---|---|---|
slots | 1 | 2 | 3 | 4 | 5 |
data | 0 | 0 | 0 | 0 | 0 |
The data inside each slot is 0 because when you create integer variables and arrays, they are automatically given the value of 0.
The Array Index
Each slot (or element) in an array is accessed by its array index. You can put data into a slot this way :
playerScores(3) = 100
This will put the number 100 in slot 3 of the playerScores array.
You can access the data in the same way. To display the contents of an array, you would use something like this code :
Print playerScores(3)
This will display the contents of slot 3 of the playerScores array.
Here is a complete example of the code presented so far.
Dim playerScores(3) As Integer
playerScores(3) = 100
Print playerScores(3)
Sleep
End
This page has been recommended for cleanup, integration, etc.