indexing

value[index [; alternate]]

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.

invalid index and alternate

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).

string indexing

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 string, not a code point. You can use the stringToCp() function to get a code point or array of code points, and the cpToString() function to convert a code point or array of code points to a string.

hash indexing

A hash may be indexed with a string, number, or Boolean.

indexing with arrays

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.

Indexing a string by an array still returns a single string.

Ranges can be used within arrays used to index arrays or strings (but not hashes).

ranges

Ranges in langur may be indicated with the .. (double dot) or to token. They are exactly equivalent.

example notes
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).