'Pine Editor If/Else and "Cannot use 'plot' in local scope"

This is my first attempt at coding with Pine Editor, and I'm trying to make make an adjustable moving average ribbon indicator that allows the user to select between increments of 1 and 2. For example, one setting that plots the 5, 6, 7, 8 and 9 averages, and another that plots 6, 8, 10, 12 and 14. I understand I will need to code an if/else condition to determine which series to plot, however, I get the error "Cannot use 'plot' in local scope" when trying this. Can someone advise me of a workaround please?

src = input(title="Source", type=source, defval=close)
increment= input(defval='1', title = "Increment", options =['1', '2'])
matype= input(defval='SMA', title = "Weighting", options =['SMA', 'EMA', 'WMA', 'VWMA','RMA', 'ALMA'])
getma(lngth)=>
    _ret = matype == 'SMA' ? sma(close, lngth) : matype == 'EMA' ? ema(close, lngth) : matype == 'WMA' ? wma(close, lngth) : matype == 'VWMA' ? vwma(close, lngth) : matype == 'RMA' ? rma(close, lngth) : alma(close, lngth, 0, 2)
    
if increment== "1"
    plot(getma(5), title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(7), title="07", linewidth=1, color=src >= getma(7) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(9), title="09", linewidth=1, color=src >= getma(9) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)


else if increment== "2"
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)
    plot(getma(12), title="12", linewidth=1, color=src >= getma(12) ? green : red, transp=88)
    plot(getma(14), title="14", linewidth=1, color=src >= getma(14) ? green : red, transp=88)
    plot(getma(16), title="16", linewidth=1, color=src >= getma(16) ? green : red, transp=88


Solution 1:[1]

So, the error message is clear. You cannot use the plot() function in local scope. What you can do is, apply your condition to the series argument of your plot() calls.

plot(increment== "1" ? getma(5) : na, title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)

So, if increment== "1" is true, it will plot the value of getma(5), else, it will not plot anything (na).

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 vitruvius