Pine Script数组删除Box元素时返回类型不兼容报错问题
Pine Script函数返回类型不兼容错误解决:array.remove引发的类型冲突
在Pine Script中定义了_extendDZbox函数,接收存储box元素的数组与_low参数,功能是把数组内的box元素向右延伸,直到蜡烛触碰box。当蜡烛触碰到box时,想用布尔型输入参数i_mz_delete_toggle控制是否用array.remove(_boxes, i)删除该box,但编译时出现报错:
Return type of one of the 'if' or 'switch' blocks is not compatible with return type of other block(s) (series box; void)
即使隔离array.remove相关代码、使用简化测试代码,错误依然存在,无法定位不兼容返回类型的来源。
原函数代码
_extendDZbox(_boxes, _low) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low < _boxHigh and bar_index == _boxRight if i_mz_delete_toggle array.remove(_boxes, i) else if i_mz_recolor_toggle box.set_right(_box, bar_index) box.set_bgcolor(_box, i_mz_color) box.set_border_color(_box, i_mz_color) box.set_text_color(_box, i_mz_label_color) else box.set_right(_box, bar_index)
简化测试代码
_extendDZbox(_boxes, _low) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low < _boxHigh and bar_index == _boxRight array.remove(_boxes, i)
问题原因
Pine Script会自动推断函数的返回值类型。你的函数中,box.set_right()这类操作会返回对应的box对象,而array.remove()是无返回值的(类型为void),这就导致函数不同分支的返回类型不匹配,触发了类型冲突报错。
解决办法
明确将函数定义为无返回值函数,在函数声明时添加=> void,告诉编译器这个函数不需要返回任何值,这样就不会再检查分支的返回类型是否一致。
修改后的原函数代码
_extendDZbox(_boxes, _low) => void if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low < _boxHigh and bar_index == _boxRight if i_mz_delete_toggle array.remove(_boxes, i) else if i_mz_recolor_toggle box.set_right(_box, bar_index) box.set_bgcolor(_box, i_mz_color) box.set_border_color(_box, i_mz_color) box.set_text_color(_box, i_mz_label_color) else box.set_right(_box, bar_index)
修改后的简化测试代码
_extendDZbox(_boxes, _low) => void if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low < _boxHigh and bar_index == _boxRight array.remove(_boxes, i)
内容的提问来源于stack exchange,提问作者Blu_Ju
相关产品推荐
相关产品推荐

