Arrays, strings, and hashes are indexed with square brackets.
Array and string indexing is 1-based.
Besides using an integer to index an array or string, you can use an integer range. Using a descending range will return the elements in reverse order.
Normally, an invalid index generates an exception.
To return an alternate value instead, inside the square brackets you follow the index with a semicolon and the alternate value.
Evaluation of the alternate value uses short-circuiting (no evaluation of complicated alternate value if not needed).
Strings are indexed by code point, not by code unit.
A descending range can be used to reverse the code points. This is not a string reversal according to Unicode rules.
Indexing a string returns a code point or array of code points. Use the s2s() function to return a string built by indexing.
You can also use the s2cp() function to get a code point or array of code points, and the cp2s() function to convert a code point or array of code points to a string.
A hash may be indexed with a string or number.
0.9 introduces a short-hand way to index by string, using a single quote mark immediately after a variable name or closing square bracket. Short-hand indexing is limited to the code points used for tokens.
.x["string"] == .x'string .y'abc == .y["abc"] .z["123"] == .z'123 .z["123"]["abc"] == .z'123'abc
Arrays, strings, and hashes may be indexed with arrays of appropriate values. For example, ["a", "b", 3, 4][[1, 4]] would yield ["a", 4] as the result.
Ranges can be used within arrays used to index arrays or strings (but not hashes).
Ranges in langur may be indicated with the .. (double dot) or to token. They are exactly equivalent.
|1 .. 7||ascending range from 1 to 7
valid for indexing
|7 .. 1||descending range from 7 to 1
valid for indexing
|3.14 .. -7.7||descending range from 3.14 to -7.7
not valid for indexing
|1 to .var||range from 1 to the value of .var
might be valid for indexing
Ranges are inclusive for both the start and end. (Some languages use exclusive reckoning for the end of a range.)
Ranges may be descending as well as ascending. This is important to indexing.
Ranges not used for indexing are not restricted to integers. For example, you might use a decimal range with the series() function (such as series 1.0 to 3.5, 0.1).
As of 0.8.3, you can index on a range to get the start and end of it (returning the same values as the first() and last() functions). As a consequence, the len() function will return 2 for a range.