Prev: Variables
Arrays
Arrays are collections of values. The array values can be of different type, and they can themselves again be arrays. The individual array elements are accessed by indexing with integer numbers, starting at 0 for the first element. Indexing requires putting the index value between brackets [], following the array variable.
Trying to access an element with a negative or too large index throws ExcIndexOutOfRange.
Function .len returns the number of elements in the array.
Arrays are created by array literals, or by functions in module array. An array literal is a comma-separated sequence of element values between brackets:
a=["One", "Two", "Three"];
print a[0] // first element
→ One
print a[2] // third element
→ Three
print len(a)
→ 3
print a[3] // there is no fourth element
→ ExcIndexOutOfRange thrown
|
Arrays in m are completely dynamic, i.e. they can grow and shrink in size. Function .append appends elements to an array:
append(a, "Four", "Five");
print a
→ [One,Two,Three,Four,Five]
|
Associative Arrays
Array values can also be indexed by strings ("keys"), making the arrays "associative" and facilitating many programming tasks. Setting or getting an array element via a string key is a fast operation[3].
Normally, keys are case sensitive, but array.new can also create arrays using case folded keys.
Unlike indexing with numbers, indexing with strings for nonexisting index values does not throw an exception:
- Getting an element for a nonexisting key returns null.
- Setting an element for a nonexisting key appends the element to the array.
Arrays with string keys can still be indexed using integer values.
In array literals, preceding an element value with a key and a colon adds the corresponding key:
h=["Joe":150, "Jack":165, "William":180, "Averell":195];
print h["Jack"]
→ 165
print h["Lucky Luke"] // element does not exist
→ null
h["Lucky Luke"]=185; // element is appended
print h
→ [150,165,180,195,185]
print h[2]
→ 180
|
See also: .append, .keys, module array.
| | |
Literal := SimpleLiteral | ArrayLiteral .
ArrayKey := Expression .
ArrayValue := Expression .
ArrayElement := [ArrayKey ':'] ArrayValue .
ArrayLiteral := '[' [ ArrayElement {',' ArrayElement} ] ']' .
Designator := Variable { Selector } [ InstanceFunctionReference ] .
Selector := '[' Expression ']' | InstanceSelector .
|
|
Next: Expressions© 2004-2011 airbit AG, CH-8008 Zürich
Document AB-M-REF-887