For loops are bounded
Pine for loops must have a known length at compile time. They cannot be infinite.
for i = 0 to 49
sum += close[i]
This sums the last 50 closes. The bound 0 to 49 is the iteration count.
While loops are single-pass
while loops in Pine execute once per bar with internal state. They cannot run across the chart history inside a single bar — there is no way to "wait for the next bar". This is the most common gotcha for people coming from Python.
The 100,000-iteration cap
Pine limits the total iterations a single bar's execution can use. If you nest a for inside a while and the inner loop runs 100,000 times, your script will throw a runtime error. The cap exists to keep the chart responsive. In practice, the cap is rarely hit unless you do something pathological.
What loops are useful for in Pine
Most Pine work is vectorised and you never need a loop. The places a for shines: building a custom rolling calculation the built-ins don't cover, scanning a small lookback window for a pattern, or iterating over an array (covered next lesson).
A pattern-recognition example
Detect a three-bar pattern: bar N's low is below bars N-1 and N-2:
threeBarLow = true
for i = 1 to 2
if low >= low[i]
threeBarLow := false
plotshape(threeBarLow, style=shape.triangleup, location=location.belowbar)
When not to use loops
If you find yourself writing for i = 0 to 9999 to scan the entire chart for something, you almost certainly want an array or a built-in function. Pine is designed so that 90% of indicator work doesn't need loops at all.