如何在Pine Script的switch语句中实现多表达式匹配?附示例代码
在Pine Script中实现switch语句的多表达式匹配
Pine Script v5的switch语法不支持在单个case里直接用or连接多个值(你写的1 or 2会被解析为逻辑运算,结果为true,和变量a=2不匹配,所以代码不会执行)。要实现多值匹配,有两种常用方法:
方法1:多case共用代码块
将需要匹配的每个值单独作为一个case,指向同一个代码块:
//@version=5 indicator("Test switch", overlay = true) if barstate.islast a = 2 switch a 1 => 2 => label.new(bar_index, high, str.tostring(a))
当a等于1或2时,都会执行label.new的代码。
方法2:使用布尔表达式作为case
如果不指定switch后的匹配变量,每个case可以是完整的布尔表达式,直接判断变量是否满足多值条件:
//@version=5 indicator("Test switch", overlay = true) if barstate.islast a = 2 switch a == 1 or a == 2 => label.new(bar_index, high, str.tostring(a))
也可以用in操作符简化多值判断:
//@version=5 indicator("Test switch", overlay = true) if barstate.islast a = 2 switch a in [1, 2] => label.new(bar_index, high, str.tostring(a))
内容的提问来源于stack exchange,提问作者Micke
相关产品推荐
相关产品推荐

