Pinescript v5 'while' loop

Viewed 38

My general understanding of a basic while loop (in other languages) is the while loop will break out itself when the variable is no longer true. This does not seem to be happening in Pine Script v5.

Example: (_RSI is less than _Min_RSI) and (_VOL is greater than _Min_VOL and less than _Max_VOL)

_switch = 0

while _switch > -1

_switch := (  (_RSI >= _Min_RSI and _RSI <= _Max_RSI) ?  1  : -1   )
    // While loop should break out automatically after this line if _switch equal to -1
_switch := (  (_VOL >= _Min_VOL and _VOL <= _Max_VOL) ?  1  : -1   )

break

When _RSI is less than _Min_RSI, _switch is correctly set to -1. But, the while loop does NOT break out automatically.......
Instead, it continues to the _VOL line. In essence the overall output is an OR whereas I'm expecting AND.

Above is a sample. The actual code has 50+ checks, for (each of) 10 time-frames. Originally I was using 50 if statements, but thought the while loop would help performance.

Seems the only workaround is to evaluate (and break out after) each line, which kinda defeats the purpose of using a while loop in the first place.

What am I doing wrong? Or does the while loop simply work differently in PS vs other languages?

Thanks

1 Answers

Answer from TradingView Support.

Correct, as we said in the previous post when the 'while' expression is checked, it goes into the 'while' scope and executes the code block, if the expression is changed from inside the local block it will only be re-checked on the next iteration of the script, but it will not break automatically in the middle of the local scope. If you want to stop the loop in the middle - use the 'break' keyword after re-assigning the value of the expression.

Clear.

Related