Cause
The script read or wrote an array element that doesn't exist. Array indices start at 0 and end at size − 1, and an array that grows bar by bar is smaller, or empty, on the first bars.
Broken code
This script compiles, but stops on the chart with the error above.
//@version=6
indicator("Oldest of the last 3 closes")
var closes = array.new<float>()
closes.push(close)
if closes.size() > 3
closes.shift()
plot(closes.get(3))Fixed code
The same script, corrected for Pine Script v6. Paste it into the Pine Editor and save.
//@version=6
indicator("Oldest of the last 3 closes")
var closes = array.new<float>()
closes.push(close)
if closes.size() > 3
closes.shift()
plot(closes.size() == 3 ? closes.get(0) : na)Why it works
The array holds at most 3 elements, at indices 0, 1 and 2, so index 3 never exists, and on the first bar the array holds only one element. The oldest close sits at index 0. Checking the size before reading avoids the error on the early bars. In the message, "xx" is the index the script asked for and "yy" the array's size at that moment.
Safe loops over an array
for i = 0 to array.size(a) - 1 breaks on an empty array, because the loop runs from 0 to -1. Loop over the elements directly instead, which does nothing when the array is empty:
float total = 0.0
for value in closes
total += value
Pine Script v6 also accepts negative indices in functions such as array.get(): closes.get(-1) is the last element. They are bounded by the size the same way.
Questions
Do Pine Script arrays start at 0 or 1?
At 0. The last element is at array.size() - 1. In v6 you can also count from the end with negative indices: -1 is the last element.
Why does the error say "Array size is 0"?
The array is empty on that bar, usually because elements are only added when a condition is met. Check array.size() before calling get(), first(), last(), pop() or shift().
The scripts on this page are minimal examples written to show the error and its fix, not trading systems. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.