functionpine-scriptundeclared-identifier

converting a function from V1 to V4 pinescript


I found a script that i would like to use and convert to V4, please see below function and errors given.

lag(g, p) =>
    L0 = (1 - g)*p+g*nz(L0[1])
    L1 = -g*L0+nz(L0[1])+g*nz(L1[1])
    L2 = -g*L1+nz(L1[1])+g*nz(L2[1])
    L3 = -g*L2+nz(L2[1])+g*nz(L3[1])
    f = (L0 + 2*L1 + 2*L2 + L3)/6
    f
lmas = lag(Short, hl2)
lmal = lag(Long, hl2)

then the errors when trying to compile to V4 :

line 214: Undeclared identifier 'L0';
line 215: Undeclared identifier 'L1';
line 216: Undeclared identifier 'L2';
line 217: Undeclared identifier 'L3'

all help will be appreciated.


Solution

  • In Pine v3, it's no longer possible to make a variable that references itself during its assignment. To convert the code to v4, you need to add several lines that create your L* variables first, and then reassign their values with the := operator:

    lag(g, p) =>
        float L0 = na
        float L1 = na
        float L2 = na
        float L3 = na
        L0 := (1 - g)*p+g*nz(L0[1])
        L1 := -g*L0+nz(L0[1])+g*nz(L1[1])
        L2 := -g*L1+nz(L1[1])+g*nz(L2[1])
        L3 := -g*L2+nz(L2[1])+g*nz(L3[1])
        f = (L0 + 2*L1 + 2*L2 + L3)/6
        f
    lmas = lag(Short, hl2)
    lmal = lag(Long, hl2)