Previous section To contents Next section

5.5 Indexing

The index and range operators are used to retrieve information from a complex data type.

Function Syntax Identifier Returns
Index a [ b ] `[] Returns the index b from a.
Lookup a ->identifier `-> Looks up the identifier. Same as a["identifier"].
Assign index a [ b ] = c `[]=; Sets the index b in a to c.
Assign index a ->identifier = c `->= Sets the index "identifier" in a to c.
Range a [ b .. c ] `[..] Returns a slice of a starting at the index b and ending at c.
Range a [ .. c ] `[..] Returns a slice of a starting at the beginning of a and ending at c.
Range a [ b .. ] `[..] Returns a slice of a from the index b to the end of a.

The index operator can be written in two different ways. It can be written as ob [ index ] or ob->identifier. However, the latter syntax is equal to ob [ "identifier" ]. You can only index strings, arrays, mapping, multisets and objects, and some of these can only be indexed on certain things as shown in this list:

Operation Returns
string[int] Returns the ascii value of the Nth character in the string.
array[int] Return the element in the array corresponding to the integer.
array[int]=mixed Sets the element in the array to the mixed value.
 Returns the value associated with the index, 0 if it is not found.
 Associate the second mixed value with the first mixed value.
 Returns 1 if the index (the value between the brackets) is present in the multiset, 0 otherwise.
 If the mixed value is true the index is added to the multiset. Otherwise the index is removed from the multiset.
 Returns the value of the named identifier in the object.
 Set the given identifier in the object to the mixed value. Only works if the identifier references a variable in the object.
 Returns the value of the named constant identifier in the program.
string[] Returns a piece of the string.
array[] Returns a slice of the array.

When indexing an array or string it is sometimes convenient to access index from the end instead of from the beginning. This function can be performed by using a negative index. Thus arr[-i] is the same as arr[sizeof(arr)-i]. Note however that this behavior does not apply to the range operator. Instead the range operator clamps it's arguments to a suitable range. This means that a[b..c] will be treated as follows:

Previous section To contents Next section