FAQ – How to loop through arrays in Pine Script?

TradingView added arrays to Pine Script just recently. There is no much example and tutorials about them. So even the simplest operation with arrays might cause some difficulties. In this article, I will show you how to iterate through an array in Pine Script using for loop.

First let’s define an array and push to it few values:

//@version=4
study("Loop through arrays")

arr = array.new_int(0)

array.push(arr, 1)
array.push(arr, 2)
array.push(arr, 3)
array.push(arr, 4)
array.push(arr, 5)

I will iterate through this array using a for loop. I’ll start with an index of 0 and end with the last index of the array (length of array minus one). To show how it works I create a string variable with all elements and display it on the chart as a label.

lab = ""
for i = 0 to array.size(arr) - 1
    lab := lab + tostring(array.get(arr, i)) + " "
    
l = label.new(bar_index, close, lab)
label.delete(l[1])

This works pretty well and you’ll see all elements of your array as a label:

To loop through array backwards you have to be a bit more creative. Issue is that you can’t write a decreasing for loop on Pine Script. But you can do that with the same loop but just simply calculating indexes backwards:

lab = ""
for i = 0 to array.size(arr) - 1
    lab := lab + tostring(array.get(arr, array.size(arr) - 1 - i)) + " "
    
l = label.new(bar_index, close, lab)
label.delete(l[1])

Now you’ll see your elements in opposite order:


Follow me on TradingView and YouTube.