plot() inside if — “Cannot use ‘plot’ in local scope” fixed · Pine Script Bug 01 #shorts

Writing plot() inside an if block makes the Pine Editor refuse the script (the error reads “Cannot use ‘plot’ in local scope.”). The Pine Script v6 manual: plot() must always be in the script’s global scope — at the beginning of a non-indented line — and scripts cannot use plot() inside if blocks, for loops or any other local scope, because the compiler needs to know about all plots during compilation. The fix keeps plot() global and moves the condition inside it: close > fast ? close : na plots close where the condition is true and na (nothing) elsewhere; plot.style_linebr keeps the gaps clean instead of joining them.

Broken:
//@version=6
indicator(“Bug 01”, overlay = true)
fast = ta.sma(close, 9)
if close > fast
plot(close)

Fixed:
//@version=6
indicator(“Bug 01”, overlay = true)
fast = ta.sma(close, 9)
plot(close > fast ? close : na, style = plot.style_linebr)

Pine Script Bug 01. Want more bug fixes? Comment CODE.

Educational example.

Your rules. Coded. · marketalgobot.com
https://marketalgobot.com

#pinescript #tradingview #coding #learntocode #marketalgobot