-
Hmmmph. My question is simple but has baffled me for a little while now. I'm making my own version of Snake and have got quite a long way towards finishing it. The one thing I need to do to finish is to manipulate some arrays.
1) How do I find the length of an array? Say the array is snakeX, I've tried Len(snakeX) and that doesn't work.
2) Having created an array, how can I change its length? When the snake grows, I need to record all the positions that it occupies, and the array that holds these values needs to grow as well. You can do the following:
Code:
Dim snakeX() As Integer
Private Sub Form_Load()
ReDim snakeX(5)
End Sub
But having set the array's length you cannot reset it with a different value.
Any help would be MASSIVELY appreciated.
Thanx,
Sam
-
by length, i take it you mean how many elements there are in it....
use this:
Length = Ubound(snakeX)
your other question...have you declared the array in a module to begin with? If you have then you will need to use Public instead of Dim the first time you declare it.
-
Arrays
First off, if you want to be able to re-size an array you have to declare it without a number. Then if you want to re-size the array you do indeed use ReDim. If you want to keep all of the valuse that are in the array you can use the "Preserve" keyword.
To find the number of elements in an array you use UBound(myArray).
e.g.
Code:
Dim snakeX() As Integer
'create a array of ten to start
ReDim snakeX(10) As Integer
'lets say it is filled up now and want to
'add some more elements while keeping the
'existing values.
'This will add 5 more values to the array
ReDim Preserve snakeX(UBound(snakeX) + 5) As Integer
Hope this helps.
-
Thanx
Thanx tons, lads. That helps loads. :D
-
You're pretty much on the ball, but one exception - this code assumes 1-based arrays:
Length = Ubound(snakeX)
The proper method is to do
Length = UBound(ary) - LBound(ary) + 1