Blitz:Arrays

From Amiga Coding
Jump to: navigation, search

An array is a collection of variables of the same type which are grouped together. An array of variables can be accessed individually by your code, typically by using an index value to reference the individual variable or element required. Arrays are named similarly to variables, and are referenced by giving an index value in brackets following the name.

Attempting to use an index outside the array's range will cause a runtime error that will be caught by the debugger, but will cause your program to crash when run normally. Therefore it's advisable to write your code in such a way that this cannot happen.


Declaring Arrays

An array must be declared, or dimensioned, before it can be used by your code. To do this you use the Dim statement:

Dim a(25)

The number in brackets is the number of the highest index to be used. The first index is 0 so the code above actually results in an array with 26 elements with indices 0 to 25.

Multi-dimensional arrays can also be declared by providing the size of each dimension separated by commas. For example:

Dim MyMatrix(100, 50)

This sets up an array called MyMatrix with is 100 by 50 in size. Any number of dimensions can be used, just remember that the memory required is multiplied with each dimension. For example, an array of 100x100x100x100 long, quick or float elements is close to 400MB in size!

Multiple arrays can be declared at once, for example:

Dim MyMatrix(100, 50), results(25)


Accessing Elements

Individual elements work in much the same way as variables. For example:

Dim MyArray(10)
MyArray(3) = 16
MyArray(5) = 24

NPrint MyArray(2)
NPrint MyArray(3)
NPrint MyArray(5)

This example will give the following output:

0
16
24

The 0 is printed because all elements are initially set to 0 by the Dim statement, and nothing has changed the value of element 2 in the code.


Resizing Arrays

Arrays can be resized by "re-dimming" the array. This also has the effect of completely erasing the array's contents, so can be used as a convenient way of resetting an array's elements to 0. To do this, just repeat the Dim statement with the new size required, or with the original size just to reset it:

Dim a(10)
a(2) = 5
Dim a(7)
NPrint a(2)

This will output 0, since the array has been reset. The new array also only goes up to index 7 instead of the original limit of 10.

In AmiBlitz 3, the current contents of an array can also be kept when resizing by using the KEEP keyword in association with the Dim statement. This will leave the previous contents intact for all elements also in the new sized array. If the new size is smaller, the contents of the extra elements will be lost. If the new size is bigger, the new elements will be set to 0 and all old elements will be kept. For example:

Dim a(10)
a(3) = 50
a(7) = 25

Dim KEEP a(6)

In this case, a(3) still contains 50, but a(7) is lost as the array now only goes up to index 6.


NewType Arrays

Arrays can be created for any type of variable, including NewTypes. Again, these work much the same way as individual variables:

NEWTYPE .ship
  name.s
  energy.l
  x.w
  y.w
End NEWTYPE

Dim enemies.ship(50)

For i = 1 To 50
  enemies(i)\name = "Enemy " + Str$(i)
  enemies(i)\energy = 100
  enemies(i)\x = i * 10
  enemies(i)\y = 25
Next i

This example defines a NewType for .ship, then sets up an array of 50 ships to hold the details of the enemies. Following that, a loop sets each ship's name to "Enemy 1", "Enemy 2" etc. up to "Enemy 50". It also sets its energy to 100, then its x coordinate to a multiple of the loop variable, and the y coordinate to 25. This places the ships in a line across the imaginary playfield.


List Arrays

List arrays, or linked lists, are a special type of array that do not use indices. Instead, they hold a current element in memory, and jump through the list of elements relative to the current item. This makes them well suited to use in situations where the number of elements actually used is variable, and where your program cycles through the elements. For example, an address book or a list of files. Due to how list arrays work, they are generally faster to use than traditional arrays.

List arrays can only be one dimension, but can be of any data type including NewTypes. Possible movements are:

  • Next item
  • Previous item
  • Jump to first item
  • Jump to last item
  • Reset to no current item (before first item)

Items are added to the array either at the end of the list, or inserted at the current position, pushing the old current item and all further items one position down the list. Items can be added up to the maximum size given when the array was declared, after which adding items will fail. Items can also be removed from the list, pulling all subsequent items up one place to fill in the gap left by the removed item.


Declaring Lists

To declare an array as a list type, the LIST keyword is used in the Dim statement:

Dim LIST a(10)

This defines an empty list of values with a maximum of 10 items.


Navigating Lists

Lists are navigated by moving forwards or backwards through the list using the relevant functions shown in the example below. When initialised, a list does not have any current item so you must navigate to at least one item before you attempt to access any elements.

Dim LIST a(10)
For i = 1 to 5
  If AddItem(a()) ; Try to add an item to the list at the current position, or the start if the list is empty
    a() = 10 * i
  Else
    NPrint "Error adding item to list!"
  End If
Next i

ResetList a() ; Resets current item to undefined

While NextItem(a()) ; Execute this loop whenever there's a further item in the list
  NPrint a()
End While

This code sets up the list array and adds 5 items to it which are multiples of 10. It then resets to the start and uses a While loop to move to each item in turn, printing its value. A While loop is used because it will not execute the code if there isn't a next item. So, if the list is empty it won't try to execute even once, and if the list does contain elements, it will only execute up until the last item is selected.

Most of the navigation commands return a true or false result so you can tell whether it worked or not. It is very important to check for the success of these commands as if they fail for any reason (list full, not enough free RAM etc.), attempting to access the failed element will cause a crash.


Accessing Lists

Lists are accessed as a normal array, but with empty brackets as shown in the example above.

Note: Blitz will not give you an error if you use an index to access elements of a list, and it may even appear to work in many cases. But due to how they work internally this will often not work, especially in cases where items are inserted or removed. Unexpected behavior or crashes could result from using an index with a list array!


List Control and Navigation Commands

result = AddItem(a())
Attempts to insert an item to the list array a() at the current position, or at the first position if the list is empty. The original current item (if it exists) and all subsequent items will be moved one position down the list to make space for the new item. Returns True (-1) for success or False (0) if it fails. Failure may be due to the list being full or lack of memory.
result = KillItem(a())
Attempts to remove the current item from the list array a(). Subsequent items will be moved up one place to fill in the gap left by the removed item. Returns True (-1) for success or False (0) if it fails. Failure may be due to the list being empty or no current item selected.
ResetList a()
Resets current item of list array a() to its initial state, i.e., prior to the first item. No item is selected as the current item. Does not return a result and will not fail.
result = FirstItem(a())
Jumps to the first item of the list a(). Returns True if it succeeds or False if it fails. Will fail if the list is empty.
result = LastItem(a())
Jumps to the last item of the list a(). Returns True if it succeeds or False if it fails. Will fail if the list is empty.
result = NextItem(a())
Jumps to the next item in the list a(). Returns True if it succeeds or False if it fails. Will fail if the current item is already the last item or if the list is empty. Will jump to the first item if there is no current item.
result = PrevItem(a())
Jumps to the previous item in the list a(). Returns True if it succeeds or False if it fails. Will fail if the current item is the first item or if the list is empty.
ClearList a()
Clears all items from list a(). The same as re-dimming the list with the same parameters.


Dynamic Lists

AmiBlitz added the ability to declare a list array as dynamic, i.e. automatically resized. In this case there is no practical limit to the number of items the list can hold - the memory required is allocated and freed automatically as required, so the list size is only limited by the amount of RAM available.

To define a list as dynamic, declare it with a size of 0:

Dim LIST addresses(0)

All normal navigation and control commands will also work on dynamic lists.