Friday 20 April 2012

Object Storage 2

To convert the temp array data to the object array, we need to first dim the object array.

In the LoadObjectData() function, change the line.
game.topObject = 0
to
game.topObject = thisArraySize
Which now sets the top object to match the number of lines read into the temp array.

Immediately after, add the line.
dim MainObject[ topObject() ] as MainObjectType
Which now prepares the object array for the correct number of objects.

Next is a for/next loop to copy the data into the array.
for i=1 to topObject()
   thisString$ = tempArray[ i ]
   thisLen = len( thisString$ )
   thisComma = FindSubString( thisString$ , "," , 1 )
   if thisComma > 0
      MainObject[ i ].name$ = left( thisString$ , thisComma - 1)
      thisString$ = right( thisString$ , thisLen - thisComma )
      MainObject[ i ].icon = val( thisString$ )
      MainObject[ i ].isKnown = 0
   endif
next i
First, this copies the contents of position i in the temp array into local variable thisString$ and gets the length of this string and stores it in thisLen.

Using these local variables not only makes the rest of the code more readable, but it helps track down any problems if the routine doesn't work as it should.

The comes the string search, which looks for a comma, storing the result in thisComma.

If the result is greater than zero - ie a comma was found, then it processes the line further. We will come back to what happens if it doesn't find one in a bit, for now it just moves onto the next string.

Within the conditional loop, it uses the left() command to extract the portion of the string before the comma, putting it into the name field of the object array at position i.

Then it removes both the left portion and the comma, by using the right() command to extract the part after the comma, putting the result back into thisString$.

It obtains the value of the remainder of the string and places this in the icon field of the object array - again at position i.

Finally, it sets the isKnown field to zero, as all objects are unknown to begin with.

The conditional block ends with the endif and moves onto the next object with the next command.

The final step is to remove the two slashes from the line.
//      dim tempArray[ 0 ]
Which changes it from a comment into an active command.  This command now clears the temp array.

Compile and run the code and you should get.
Showing that the object array is now populated with the correct information.

No comments:

Post a Comment