[]
in pine-script is called History Referencing Operator. With that, it is possible to refer to the historical values of any variable of a series type (values which the variable had on the previous bars). So, for example, close[1]
returns yesterday's close price -which is also a series.
So, if we break your code down (starting from the very first bar):
testfu(x,y)=>
sum = 0.0 // You set sum to 0.0
sum:= 1+ nz(sum[1]) // You add 1 to whatever value sum had one bar ago
// which is 0, because it's the first bar (no previous value)
sum // Your function returns 1 + 0 = 1 for the very first bar
Now, for the second bar:
testfu(x,y)=>
sum = 0.0 // You set sum to 0.0
sum:= 1+ nz(sum[1]) // You add 1 to whatever value sum had one bar ago
// which is 1, because it was set to 1 for the first bar
sum // Your function now returns 1 + 1 = 2 for the second bar
And so on.
Have a look at the following code and chart. The chart has 62 bars, and sum
starts from 1
and goes all the way up to 62
.
//@version=3
study("My Script", overlay=false)
foo() =>
sum = 0.0
sum:= 1 + nz(sum[1])
sum
plot(series=foo(), title="sum", color=red, linewidth=4)