Pine Script v5中if块与else块为何需强制返回类型匹配?
问题
我在研读TradingView Pine Script官方文档的数组章节示例代码时,注意到代码里有一行注释// Force the return type of this 'if' block to be the same as that of the next block.,想知道为什么必须这么做?
示例代码
//@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()
回答
这是因为Pine Script对if-else分支的返回类型有严格要求:同一个if-else结构下的所有分支,必须返回相同类型的值,否则会触发编译错误。
拆解代码里的两个分支来看:
- 第一个
if分支执行lows.push(low),这是数组添加元素的操作,返回的是void(无返回值); - 第二个
else if分支最后执行flushLows := true,这是赋值操作,返回的是bool类型的结果。
两者返回类型不匹配,编译器会直接报错。加上bool(na)后,第一个分支就会返回一个bool类型的空值(na是Pine Script中各类型通用的空值),让两个分支的返回类型统一,从而通过编译。
内容的提问来源于stack exchange,提问作者tino
相关产品推荐
相关产品推荐

