Edgoro
Compile error · Scope

Pine Script: Cannot modify global variable in function (fix)

Pine Script functions can't reassign global variables with :=. Return the value instead, or keep state in an array or object. Examples in v6.

Pine Editor console · line 6
Cannot modify global variable "count" in function

Cause

Inside a user-defined function, the script tries to change a variable declared at the top level with :=. Functions can read global variables but can't reassign them.

Broken code

TradingView reports the error on line 6.

Pine Script v6
//@version=6
indicator("Signal counter")
var int count = 0
countSignal(cond) =>
    if cond
        count := count + 1
countSignal(ta.crossover(close, ta.sma(close, 20)))
plot(count)

Fixed code

The same script, corrected for Pine Script v6. Paste it into the Pine Editor and save.

Pine Script v6
//@version=6
indicator("Signal counter")
var int count = 0
signalValue(cond) =>
    cond ? 1 : 0
count += signalValue(ta.crossover(close, ta.sma(close, 20)))
plot(count)

Why it works

Functions in Pine Script compute and return values. Return what changed and do the assignment at the top level, where the global variable lives. To return several values, end the function with a tuple, [a, b], and unpack it with [x, y] = f().

Keeping state in an array or object

A variable that holds an array, a map or an object of a user-defined type can be updated through its methods inside a function, because the function changes the collection, not the variable:

var hits = array.new<int>()
record(cond) =>
    if cond
        hits.push(bar_index)
record(close > open)
plot(hits.size())

Questions

How do I return several values from a Pine Script function?

Return a tuple from the last line, [value1, value2], and unpack it where you call the function: [a, b] = myFunction().

Can a Pine Script function keep its own state between bars?

Yes. A var variable declared inside a function keeps its value from bar to bar, separately for each place in the script where the function is called.

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.

Still getting an error?

Paste your script and the message into the free Pine Script error fixer: it explains what went wrong and returns a corrected v6 version. Or describe the indicator in plain English and let Edgoro write the code.