Creating and using 2-D Arrays
Definition
If 1-D Arrays are like lists of objects, 2-D Arrays are like grids. Instead of using an integer as an index, these data structures use a pair of integers of the form (a,b).
A way to visualize an array is to think of an egg carton. Each slot in the egg carton holds one element, and it can be accessed using a row and column indexes. Yummy, right?
Declaration
This declaration creates a 2-D Array of 10 by 10 members. ' declaration
ReDim myArray2D(10,10)
Assigning Values
Here we are assigning a string ("hey") as a value to the position (0,0) of the array. ' assignment
myArray2D(0,0) = "hey"
Accessing Values
Values can be printed, or assigned to other variables. Notice than when we try to access a member that hasn't been assigned we get an error. ' accessing
Rhino.Print myArray2D(0,0)
Dim x : x = myArray2D(0,0)
Rhino.Print x
>> hey
>> hey
Rhino.Print myArray2D(0,1)
>> Error: String required
Using iteration to populate a 2-D array
We can use our previous knowledge about points, 1-D arrays and For Loops to create a 2-D array that stores a grid of points. ReDim my2DArray(20,20)
Dim i, j
For i = 0 to 20
For j = 0 to 20
my2DArray(i,j) = array(i, j, 0)
Rhino.Print Rhino.pt2Str my2DArray(i,j)
next
next
Common problems
Subscript out of range error
Remember that array indexes start at 0, therefore the number of elements in an array is one more than its upper bound UBound(myArray).