Skip to main content

Switch Statement

The switch statement consists of the following new keywords:

  • case
  • switch
  • default
local value = 1
switch value do
case 1:
print("There is only one!")
break
case 2:
print("There is only two!")
break
end
-- Break jumps here.

Switch statements also support fallthrough.

local value = 1
switch value do
case 1:
case 2:
case 3:
case 4:
case 5:
print("Got 1-5.")
break
default:
print("Value is greater than 5.")
end
-- Break jumps here.

In this example, cases 1-4 fall through to case 5.

Remember to use break whenever you do not want fallthrough. Here is an example of a potential bug:

local value = 1
switch value do
case 1:
print("There is only one!")
case 2:
print("There is only two!")
end

-- Output:
-- There is only one!
-- There is only two! --> Uh oh.

The default case is executed if none of the other cases are true. For example:

local value = 1
switch value do
case 2:
case 3:
break

default:
print("Value is neither 2 nor 3!")
end

The default case can be placed anywhere in the statement. It also supports fallthrough, so remember to use break if you place it above any cases.

Try It Yourself

Case Statement

Any expression can be used for the case statement:

switch true do
case 42 == 42:
print("42 is 42 is true")
break
end

However, note that method calls needs to be encapsulated with parentheses:

local t = {
function getVal()
return 42
end
}
switch 42 do
case t:getVal(): -- This is interpreted as case t: getVal():print...
print("val is 42")
break
case (t:getVal()):
print("val is 42")
break
end

Using Compatibility Mode?

You may need to use pluto_switch instead of switch.