value[index]
Lists, strings, and hashes are indexed with square brackets.
List and string indexing is 1-based.
Besides using an integer to index an list 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.
value[index; alternate]
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 list 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 list of code points, and the cp2s() function to convert a code point or list of code points to a string.
A hash may be indexed with a string or number. Note that "1" is a different index than 1.
As a short-hand way to index by string, use 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.
# All the following are true. .x["string"] == .x'string .y[123]'abc == .y[123]["abc"] .z["123"] == .z'123 .z["123"]["abc"] == .z'123'abc
Lists, strings, and hashes may be indexed with lists of appropriate values. For example, ["a", "b", 3, 4][[1, 4]] would yield ["a", 4] as the result.
Ranges can be used within lists used to index lists or strings (but not hashes).
Ranges in langur may be indicated with the .. (double dot) operator.
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 .. .var | range from 1 to the value of .var might be valid for indexing |
'a' .. 'z' | code point (integer) range valid for indexing |
"a" .. "z" | string range not valid for indexing |
dt/2020-10-1/ .. dt/2020-11-01/ | date/time range not valid for indexing |
dr/20y/ .. dr/30y/ | duration range not valid for indexing |
Ranges are inclusive for both the start and end.
The start and end must be of the same type and must be comparable with > or < type operators. Ranges may be made of numbers (including code points), strings, date-times, or durations.
Ranges may be descending as well as ascending.
Number 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 .. 3.5, 0.1).
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.