生生不息

生生不息

pine替代ifelse的switch语法

2025-07-20
pine替代ifelse的switch语法

背景

pine switch替代 ifelse多选项输入

代码

pine脚本记录

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=6
indicator("switch")
i_maType = input.string("EMA", "MA Type", options = ["EMA", "SMA", "RMA", "WMA", "?"])

f_getMA(_maType, _maSource, _maLength) =>
    switch
        _maType == "SMA" => ta.sma(_maSource, _maLength)
        _maType == "EMA" => ta.ema(_maSource, _maLength)
        _maType == "WMA" => ta.wma(_maSource, _maLength)
        _maType == "VWMA" => ta.vwma(_maSource, _maLength)
        _maType == "RMA" => ta.rma(_maSource, _maLength)
        _maType == "SWMA" => ta.swma(_maSource)
        => ta.sma(_maSource, _maLength)

ma = f_getMA(i_maType, close, 20)
plot(ma,"MA",color = color.green)

之前版本4的代码,需要对输入选项,一个if,然后else if。

正常逻辑都是这样写

不过新版本 引入了 switch 直接匹配字段,然后引向对应的执行代码。

最后的”=> ta.sma(_maSource, _maLength)“相当于 else结尾(不符合前述所有的”if“)