Here is a snippet of my pinescript version 5 code and I am trying to get the local “crossed” condition to modify the global variable “crossed” but I keep running into the error “cannot modify global variable in function”.
var bool crossed = na // Declare a global variable for the crossed condition
method puts(bool mode, array<line> a, line l) =>
crossed := false // Reset the global "crossed" variable
if mode == true
if a.size() == 500
line.delete(a.shift())
a.push(l)
if mode == false
for j = a.size() - 1 to 0 by -1
x = line.get_x2(a.get(j))
y = line.get_y1(a.get(j))
if bar_index - 1 == x - 1 and not (high > y and low < y)
line.set_x2(a.get(j), bar_index + 1)
if bar_index - 1 == x - 1 and (high > y and low < y)
crossed := true // Set the crossed condition to true
Please help. Thank you.
I tried changing the global variable to a mutable one but it also didn’t work.
The error message is clear. You cannot modify global variables in functions. Just use a temporary variable and return it. Then use the return value to change your global variable’s value.
var bool crossed = na // Declare a global variable for the crossed condition
method puts(bool mode, array<line> a, line l) =>
_crossed = false
if mode == true
if a.size() == 500
line.delete(a.shift())
a.push(l)
if mode == false
for j = a.size() - 1 to 0 by -1
x = line.get_x2(a.get(j))
y = line.get_y1(a.get(j))
if bar_index - 1 == x - 1 and not (high > y and low < y)
line.set_x2(a.get(j), bar_index + 1)
if bar_index - 1 == x - 1 and (high > y and low < y)
_crossed := true // Set the crossed condition to true
_crossed
crossed := // Call your function here