Search code examples
pine-scriptpine-script-v5tradingview-api

if..else.. block in PineScript v5 - Why force return type of the "if" block to match the "else" block?


I'm trying to understand this example code (found on Tradingview manual site in arrays) Link where i found this

Notice the code comment:

// Force the return type of this 'if' block to be the same as that of the next block.

Why is this necessary ?

//@version=5
indicator("Lows from new highs", "", true)
var lows = array.new<float>(0)
flushLows = false

// Remove last element from the stack when `_cond` is true.
array_pop(id, cond) => cond and array.size(id) > 0 ? array.pop(id) : float(na)

if ta.rising(high, 1)
    // Rising highs; push a new low on the stack.
    lows.push(low)
    // Force the return type of this `if` block to be the same as that of the next block.
    bool(na)
else if lows.size() >= 4 or low < array.min(lows)
    // We have at least 4 lows or price has breached the lowest low;
    // sort lows and set flag indicating we will plot and flush the levels.
    array.sort(lows, order.ascending)
    flushLows := true

// If needed, plot and flush lows.
lowLevel = array_pop(lows, flushLows)
plot(lowLevel, "Low 1", low > lowLevel ? color.silver : color.purple, 2, plot.style_linebr)
lowLevel := array_pop(lows, flushLows)
plot(lowLevel, "Low 2", low > lowLevel ? color.silver : color.purple, 3, plot.style_linebr)
lowLevel := array_pop(lows, flushLows)
plot(lowLevel, "Low 3", low > lowLevel ? color.silver : color.purple, 4, plot.style_linebr)
lowLevel := array_pop(lows, flushLows)
plot(lowLevel, "Low 4", low > lowLevel ? color.silver : color.purple, 5, plot.style_linebr)

if flushLows
    // Clear remaining levels after the last 4 have been plotted.
    lows.clear()

Solution

  • Pine Script supports using an if for its value (as far as I can tell from the language reference, this isn't "expression if", but just a specific case that an "if statement" is allowed to have a variable assignment before the word if). The value assigned is either the last expression in the "then" block or the last expression in the "else" block, depending on which one actually executes.

    The manual notes that the types of the two blocks have to match, and that becomes the type of the if statement. That's pretty natural for a typed language. This restriction is apparently true even if there is no assignment. The reference calls that "ignoring the value of an if statement", but even if the value is ignored, it still has to type-check.