2.3.4.1. - Associative Arrays
With associative arrays, the array index expression can be any numeric or string-valued constant or expression. Associative array element values can be numbers or strings. For two-dimensional associative arrays, the two array indices for each element are stored as a single string formed using the string value of the first index, followed by the character
\034
, followed by the string value of the second index.
One can access such a 2D array element using a single index constructed
according to the above recipe.
That is,
arr["list"]["one"]
refers to the same item as
arr["list\034one"]
. Associative arrays can be initialized by assignment, as in
1.FOURC> x = [ "one@:@now", "two@:@is", "three@:@the", "three@:0:@time" ]
2.FOURC> print x
x["one"] = "now" x["three"] = "the" x["three"]["0"] = "time" x["two"] = "is" 3.FOURC>
Here
x
is either an uninitialized variable or an existing associative array.
If
x
already existed as something other than an associative array, the
above assignment statement would produce an error.
Note that one- and two-dimensional initializers can be mixed.
Note also
that the
print
command sorts the elements by index.
The index specifiers are optional for 1D arrays in the initialization.
If not used, the position in the list is used as the index, starting at zero.
1.FOURC> x = [ "now", "is", "the" ]
2.FOURC> print x
x["0"] = "now" x["1"] = "is" x["2"] = "the" 3.FOURC>
The values of associative array elements are saved in the state file, so are retained across spec sessions, unless starting fresh.
All built-in global arrays, such as those that hold motor positions and scaler counts, are associative arrays.
A number of built-in functions take associative arrays as arguments or return associative arrays as results. For example,
split()
, rsplit()
and
match()
place results in an associative array passed as
an argument.
The
move_info()
function returns a one- or two-dimensional associative array
depending on how it is called.
The
fmt_read()
and
fmt_write()
functions pass file header elements using associative arrays.
The internal code always uses the string value for the index of an associative array. Thus,
arr["12"]
refers to the same element as
arr[12]
, but
arr[012]
is not the same element as
either
arr[12]
or
arr["012"]
. The value 012 is an octal number, which is equal to a decimal 10,
so
arr[012]
is the same element as
arr[10]
or
arr["10"]
.