for … to
total = 0.0
for i = 1 to length
total := total + close[i]
for i = start to enditeratesifromstarttoendinclusive.- When
end < start, iteration counts down. - Both bounds are evaluated once at the start of the loop; a change inside the body does not affect iteration count.
Explicit step with by
for i = 0 to 100 by 10
log.info(str.tostring(i))
byis the step magnitude (always positive).- Direction is still inferred from
start/end.
for … in
Walks an array:
prices = array.from(100.0, 101.5, 102.0, 103.25)
sum = 0.0
for value in prices
sum := sum + value
Walk with index as well:
for [index, value] in prices
log.info(str.tostring(index) + " → " + str.tostring(value))
while
i = 0
remaining = volume
while remaining > 0 and i < 10
remaining := remaining - 1000
i := i + 1
Use while when the loop may terminate on a condition that is tested each iteration. Every loop carries a guard of 100,000 iterations per loop per bar: when it trips, that loop exits and the script continues with the next statement (no error is raised). Nested loops are guarded independently.
break and continue
Both work inside any of the three loop forms:
for i = 0 to 100
if close[i] == 0 or na(close[i])
continue // skip this iteration
if close[i] > close[0] * 2
break // stop the loop entirely
log.info(str.tostring(close[i]))
Loops as expressions
A loop can produce a value — the result is the value of the last iteration's final statement:
maxGap = for i = 1 to 20
math.abs(close[i] - close[i - 1])
If the loop never iterates (empty range), the result is na.
Compile-time safety
- A loop whose body uses a series-mode function (
ta.sma,ta.rsi, …) does not turn that function series-mode-safe — the function still needs to be called on every bar from the top level. The compiler emits a warning. for … inovernais a no-op.- Modifying the loop array inside a
for … inis undefined behaviour; prefer building a new array and swapping references.
See also
- Arrays — the typical loop target
- Maps — walk key/value pairs
- Execution model — why loops don't replace
[n]