Blitz3D+ Command Reference

Dim array(size[,size2,...])

Parameters

array - the array's name, with an optional type tag ($, #) or custom Type for the elements

size - highest index of the first dimension; the array gets size+1 slots, numbered 0 to size

size2 (optional) - highest index of a second dimension, and so on for further dimensions

Description

Creates an array.

Dim tile(15) gives you tile(0) through tile(15) - sixteen slots, because the index starts at zero. Tag the name to change what the slots hold: Dim name$(9) for strings, Dim speed#(9) for floats, Dim ship.Ship(9) for objects of a custom Type.

Extra sizes make a grid, which is how most tile maps are stored: Dim map(63,63), then map(x,y) is the tile at that square. The sizes are ordinary expressions worked out when the Dim runs, so Dim map(levelW,levelH) is perfectly fine.

Arrays are shared by the whole program. A Dim has to run in the main program - trying to create one for the first time inside a Function fails with "Array not found in main program" - and after that every function can read and write it without any Global declaration.

Run Dim on the same array again to resize it, for instance when the next level has a bigger map. The number of dimensions and the element type must match the first Dim, and the contents are thrown away: every slot comes back as 0, "" or Null. There is no way to resize an array and keep what was in it - copy it out first if you need the old values.

Watch the bounds. Reading or writing outside the array raises "Array index out of bounds" when you run in debug mode, but with debug switched off there is no check at all and you will be scribbling over memory, which usually shows up as a crash somewhere else entirely. Do your testing with debug on.

There is a lighter alternative for small fixed runs of values, the Blitz array: Local slots[7] declared like an ordinary variable. Its size has to be a constant, Original mode allows a single dimension only, and it cannot be resized - but it can be a Field inside a Type and it can be passed to a function, neither of which a Dim array can do.

See also: Global, Local, Const, Type, Data.

Example

; Dim Example
; -----------

; Dim creates an array - here, five inventory slots (indexes 0 to 4)
Dim inventory$(4)

; Fill the slots
inventory$(0)="Sword"
inventory$(1)="Shield"
inventory$(2)="Potion"
inventory$(3)="Map"
inventory$(4)="Lantern"

; Array elements are accessed by index, starting at 0
Print "Your inventory:"
For slot=0 To 4
    Print "    Slot "+slot+": "+inventory$(slot)
Next

Print ""
Print "Press any key to close the example"
WaitKey

End

Index