mirror of
https://github.com/opentffoundation/opentf.git
synced 2025-12-19 17:59:05 -05:00
website: "element" function supports negative indices
We got this new functionality from an upgrade of the upstream cty library, but we didn't update the docs to mention it. The examples in this doc were also evidently generated with a much older version of OpenTofu's predecessor, because the illustrated output was not shown as a quoted string. The example output now matches how the current version of "tofu console" would describe these results. Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
This commit is contained in:
@@ -12,33 +12,42 @@ element(list, index)
|
||||
```
|
||||
|
||||
The index is zero-based. This function produces an error if used with an
|
||||
empty list. The index must be a non-negative integer.
|
||||
empty list.
|
||||
|
||||
Use the built-in index syntax `list[index]` in most cases. Use this function
|
||||
only for the special additional "wrap-around" behavior described below.
|
||||
|
||||
## Examples
|
||||
|
||||
If the given index is less than the length of the given list then this
|
||||
function is equivalent to the normal index operator:
|
||||
|
||||
```
|
||||
> element(["a", "b", "c"], 1)
|
||||
b
|
||||
"b"
|
||||
> ["a", "b", "c"][1]
|
||||
"b"
|
||||
```
|
||||
|
||||
However, this function exists mainly for the special way it treats indices that
|
||||
are out of range for the list's length, which would therefore cause an error
|
||||
if used with the normal index operator.
|
||||
|
||||
If the given index is greater than the length of the list then the index is
|
||||
"wrapped around" by taking the index modulo the length of the list:
|
||||
|
||||
```
|
||||
> element(["a", "b", "c"], 3)
|
||||
a
|
||||
"a"
|
||||
```
|
||||
|
||||
To get the last element from the list use [`length`](../../language/functions/length.mdx) to find
|
||||
the size of the list (minus 1 as the list is zero-based) and then pick the
|
||||
last element:
|
||||
This wrap-around behavior also works in the negative direction, so you can
|
||||
use negative indices to select elements relative to the end of the given
|
||||
list:
|
||||
|
||||
```
|
||||
> element(["a", "b", "c"], length(["a", "b", "c"])-1)
|
||||
c
|
||||
> element(["a", "b", "c"], -1)
|
||||
"c"
|
||||
```
|
||||
|
||||
## Related Functions
|
||||
|
||||
Reference in New Issue
Block a user