Loops over every element of an array, or every key-value pair of a map, with an optional index.
for item in collection runs the block once per element, in order, with item holding the element. for [index, item] in collection adds the zero-based position. With a map, the tuple form gives [key, value]. The loop reads the collection as it goes, so if the block adds or removes elements the loop sees the change.
Like for, it returns the last value of the block, and break and continue work the same way. It is cleaner than an index loop when you do not need the position, and it cannot run past the end of the array.
Syntax
[variables = | :=] for item in collection_id statements | continue | break return_expression [variables = | :=] for [index, item] in collection_id statements | continue | break return_expressionRemarks
- Changing the loop variable does not change the array: item is a copy of an element, not a reference, for the basic types.
- On Sidechair: for...in walks arrays, with the index form giving the position. On a map it walks the keys, and the [index, item] form gives the position and the key, not the key and value.
Example
//@version=6
indicator("For in")
changes = array.new<float>()
for i = 0 to 9
changes.push(nz(close[i] - close[i + 1]))
up = 0
total = 0.0
for [i, c] in changes
if c > 0
up += 1
total += c
plot(up, "Up bars of 10", color.green, style = plot.style_columns)
plot(total, "Net change", color.blue)See also
Runs on Sidechair