'Insert a counter variable inside a IFF statement doesn't work

I'm trying to code a script where a counter increment of 1 every time one condition is false, otherwise it's equal to 0. The condition is a boolean output of the function CROSS().

I've tried:

1° version

var countSma50 = 0
countSma50_=countSma50
iff(cross(open, sma(close, 50)), countSma50=0, countSma50=countSma50_+1)

but when I plot countSma50 I obtain a line adding 1 from the first bar of the chart up to the last, countSma50 never return to 0.

or

2°Version

 if cross(close,sma(close, 50))==true
      countSma50+=1
   else
      countSma50=0

but the compiler return to me " Syntax error at input 'countSma50'."

The two script give me errors or wrong counter value..

The goal is to create a counter increasing of 1 at every bar, resetting itself every time the close crosses under/above the single moving average (sma).

Anyone can help me?



Solution 1:[1]

The second version was almost there, note that variables declared in the local scope are not visible from the global context of the script, declare the variable in the global scope first and re-assign later, the script below reset the value to 0 if there is a cross() trigger, otherwise will keep counting every bar:

//@version=4
study("My script")

var int countSma50 = 0

if cross(close,sma(close, 50))
    countSma50 := 0
else
    countSma50 += 1

plot(countSma50)

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 e2e4