You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:21:13