Arrays

BlitzMax Forums/BlitzMax Beginners Area/Arrays

pc_tek(Posted 2011) [#1]
I have the following code...


Graphics 640,480
Global map:Byte[1,7,4]
Local x:Byte,y:Byte

RestoreData LEV_Data
For y=0 To 4
	For x=0 To 7
		ReadData map[0,x,y]
	Next
Next
End

#LEV_Data
DefData 08,01,02,08,08,03,04,05
DefData 00,00,00,18,18,00,00,08
DefData 00,00,00,18,18,00,08,00
DefData 08,00,00,18,18,00,00,00
DefData 00,08,00,08,08,00,08,00



But the compiled prog spits an error out:

RUNTIME ERROR:Attempt to index array element beyond array length

Something so basic...and it confuses the hell out of me!!!


GfK(Posted 2011) [#2]
You're defining an array with 1x7x4 elements, which are numbered 0, 0-6, and 0-3. Your For/Next loops need to reflect this.


Czar Flavius(Posted 2011) [#3]
Arrays are zero-indexed. That means an array of size 4 has elements 0, 1, 2, 3. But not 4.

The for loop using to, goes up to and including that number.

So your for loop for y for example, will use the number 4, which is is above the highest index of 3.

You need to loop "To" 4-1, OR you can use For y = 0 Until 4. Until will go up to, but not including that number.

Also, there is no need for your counting variables of x and y to be bytes. It will not save any memory or give you any speed. You should use Int for general purpose numbers instead of micromanaging. Bytes for mass data is ok.


pc_tek(Posted 2011) [#4]
Usually, a dim statement of (1,7,4) would yield a 0-1,0-7,0-4 array. I say usually because I am used to Blitz3d.


Czar Flavius(Posted 2011) [#5]
It's changed from Blitz3D. That dim would give an array of 1, 1-7, 1-4 as 0 wouldn't be valid. In BlitzMax it's the same expect the index is just -1. So 0-6 versus 1-7 index for an array of size 7.


Jesse(Posted 2011) [#6]
if you feel more comfortable you can do it like this:
Graphics 640,480
Global map:Byte[1,7,4]
Local x:Byte,y:Byte

RestoreData LEV_Data
For y=0 Until 4
	For x=0 Until 7
		ReadData map[0,x,y]
	Next
Next
End

#LEV_Data
DefData 08,01,02,08,08,03,04,05
DefData 00,00,00,18,18,00,00,08
DefData 00,00,00,18,18,00,08,00
DefData 08,00,00,18,18,00,00,00
DefData 00,08,00,08,08,00,08,00