NAME

Array base class

ABSTRACT

This pod file documents the Array base class usage. For implementation details you should look inside the class file, found at src/pmc/array.pmc in the parrot source code.

SYNOPSIS

  new $P0, 'Array'    # initialize P0 as an array

  set $I0, $P0        # set I0 to the size of the array in P0
  set $P0, 2          # set the size of the array in P0 to 2

  set $P0[0], "foo "  # put "foo" into the array at position 0
  set $I1, $P0[1]     # get an integer value from the entry 
                      # at array position 1

  defined $I2, $P0[1] # is the value at position 1 defined?
  exists  $I3, $P0[0] # is there an element at position 0?

DESCRIPTION

Creation

As with any other PMC, the following line creates an array PMC in register P0:

  new $P0, 'Array'

Array sizes

You can retrieve the size of the array using

  set $I0, $P0

This will put the size of the array in register P0 into I0. In the same way, assigning an integer directly to the array sets the size of the array. For instance:

  new $P0, 'Array'
  set $P0, 2

creates a new Array (with default size 0) and then expands the size of the array to two.

Arrays do not automatically resize themselves when you access out-of-bounds elements. This means that you must remember to size an Array appropriately before storing anything in it.

Accessing elements

Elements are accessed using indexes, as in any programming language.

The following code initializes an array in P0 with size two, and sets the first position to the integer -8 and second position to the floating point number 3.1415.

  new $P0, 'Array'
  set $P0, 2

  set $P0[0], -8
  set $P0[1], 3.1415

You can also assign directly from registers; for instance:

  new $P0, 'Array'
  set $P0, 2

  set $I0, -8
  set $N0, 3.1415

  set $P0[0], $I0
  set $P0[1], $N0

leaves P0 in the same state as in the previous code snippet.

To retrieve elements, we use the same syntax:

  set $N1, $P0[1]
  set $I1, $P0[0]

Those two lines retrieve the values from the array back into registers.

The value stored at a given position is not fixed; it can be changed simply by assigning a new value:

  set $P0[1], "A string"

Accessing an out-of-bounds array element raises an exception; if you want an Array that will automatically resize, then use a ResizablePMCArray.

You can test if there is a defined element at an array position by using

  defined $I0, $P0[1]

for the position you want to test. On the other hand, if you only want to test whether a given element exists (rather than whether it is defined), then use the exists op instead:

  exists $I0, $P0[0]

TODO

Explain a little more which exception will be raised in case you access a out-of-bounds index on the array (as soon we have exceptions).