'History referencing in Pine Script arrays

I have been trying to use array feature, which recently has been introduced in PineScript 4, but it seams that either I'm not aware of its limitations, or , possibly the implementation is still buggy. The problem I'm faced with is illustrated by the following very simple script:

//@version=4

study("TEST")

// A is basically the same as bar_index+1, and it is plotted as expected
A=0
A:=nz(A[1])+1

// the same thing implemented using arrays nevertheless doesn't work as expected
B=array.new_float(1,0)
array.set(B,0,nz(array.get(B,0)[1])+1)

plot(A,color=color.red)
plot(array.get(B,0),color=color.yellow)

According to my understanding both A and the first element of B array must produce identical graphs. Nevertheless plot of B simply gives 1 on all bars. The problem is definitely related to the usage of history referencing operator []. Does anybody know how to overcome this kind of issue?

Note: I've made this script as simple as possible in order to get to the guts of the problem. The script I'm working on is much more complex, and it uses arrays inside for-loops in various ways, including the one that has been just illustrated (i.e. history referencing op), so using simple variables in place of array simply doesn't work for me.



Solution 1:[1]

  1. Past instances of array id’s or elements cannot be referenced directly using Pine’s [ ] history-referencing operator (https://www.tradingview.com/pine-script-docs/en/v4/essential/Arrays.html?highlight=array#history-referencing)
  2. Fixed version of your example:
//@version=4

study("TEST")

// A is basically the same as bar_index+1, and it is plotted as expected
A=0
A:=nz(A[1])+1

// the same thing implemented using arrays nevertheless doesn't work as expected
var B=array.new_float(1,0)
array.set(B,0,nz(array.get(B,0))+1)

plot(A,color=color.red)
plot(array.get(B,0),color=color.yellow)

Solution 2:[2]

I totally agree with you. I have problem with array historical refrencing too, which never solve by replacing of []. I rewrote my script without array and it's worked perfectly. Alas that was too long script but worked correctly. I think Pine staff should revise on arrays codes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrey D
Solution 2 Bozorgmehr Ghahari