pine-scriptpine-script-v5pine-script-v4

Cannot modify global variable in function in PineScript


This is my Pinescript code.

//@version=5
indicator("Strategy", overlay=false)

var count = 0
count := nz(count[1],0)

counter() =>
    count := close > close[1] ? count + 1 : count

counter()

plot(count)

Here I am facing an issue in my counter function. I am getting an error in the count inside my counter function. Cannot modify global variable 'count' in function; error displaying in Pinescript compiler. I tried with Var also. still facing the same issue. Please help me to resolve this.


Solution

  • The count variable should be defined inside of the function. Also, the count variable will not be available outside of the function.

    The following will work:

    //@version=5
    indicator("Strategy", overlay=false)
    
    counter() =>
        var count = 0
        count := nz(count[1],0)
        count := close > close[1] ? count + 1 : count
        count
    
    new_count = counter()
    
    plot(new_count)