So far we've only been using simple data types - which, quite often, are not enough. This section of the tutorial will introduce us to one of the ways to store values in a more compound way - arrays. An array can be thought of as a value - a structure - able to hold a number of other values. We'll see this one explained in a moment.
:set &a :arr i4 i16 i64 :writeln &a
As can be seen from the snippet above, arrays are created using the
:arr function. It can take any number of arguments, which will be placed at consecutive indexes of the array, starting from 0. Indexes of an array are always numbers - if you try to index using a different type, it will be cast silently.
Also, note that in the example the array was passed by reference (
& prefix). This is done because passing structures by value means they must be copied wholly - along with all their elements - and this can take a lot of time for large structures. Hence, it is advised to use references whenever applicable.
:set &a :arr i4 i16 i64 :writeln &a :set &a[i3] i256 :writeln &a :writeln s'a = ' $a[i0] s'; a = ' $a[i3]
Obviously, and array wouldn't be much of a use without being able to access individual elements. In awful, like many other languages, indexing an array is done using the bracket notation (
[ ]) - after the variable (array) name, we put the index we want to access in a pair of brackets. As can be seen from the example above, it is possible to both access existing ones, and create new elements using the bracket syntax.
:set &a :arr i1 i2 i4 i8 i16 i32 i64 i128 i256 :set &n i0 :writeln s'Input one number (0-10): ' :read &n :writeln s'2^' $n s' == ' $a[$n] :writeln s'2^random == ' $a[:random i0 i10] :writeln s'2^2^2 == ' $a[$a[i2]]
Array indexing is not limited only to literals. You can freely insert a variable or a whole expression into the brackets. It is even possible to use nested indexing - taking the index number from another array element (obviously, this doesn't have to be the same array).
wikipage modified on 2014/0601/2317