Sidechair

switch

Browse the reference

Picks one block to run: by matching a value against cases, or by testing conditions in order; the result is the chosen block's value.

Try it in the editor

switch expression compares the expression with each case value in turn, using ==, and runs the block of the first match. Each case is written value => block, and a case with no value, => block, is the default. The result of the switch is the last value of the block that ran, so you can assign it.

switch with no expression treats each case as a condition, and runs the block of the first one that is true. This reads better than a long else if chain. There is no fall-through: only one block ever runs. If nothing matches and there is no default, the result is na.

Syntax

[variable_declaration = ] switch expression value1 => local_block value2 => local_block … => default_local_block [variable_declaration = ] switch condition1 => local_block condition2 => local_block … => default_local_block

Remarks

  • All branches should give the same type, since the result is one variable.
  • Cases are tried top to bottom, so put specific tests before general ones.
  • On Sidechair: with an expression, a case matches when the values are equal and not na. A switch with no match returns na.

Example

Pine ScriptSwitch on an input, and on conditionsOpen in editor
//@version=6
indicator("Switch", overlay = true)
kind = input.string("EMA", "Average", options = ["SMA", "EMA", "WMA"])
avg = switch kind
    "SMA" => ta.sma(close, 20)
    "EMA" => ta.ema(close, 20)
    "WMA" => ta.wma(close, 20)
    => na
tone = switch
    close > avg => color.green
    close < avg => color.red
    => color.gray
plot(avg, "Average", tone, 2)

See also

Runs on Sidechair