Switch
The switch statement is shorthand for writing a series of if statements that check against the same value. Note that the value is only evaluated once. Like if statements, switches can have an else block to handle no matches. Comparison is done with the == operator.
MoonScript:
name = "Dan"
switch name
when "Robert"
print "You are Robert"
when "Dan", "Daniel"
print "Your name, it's Dan"
else
print "I don't know about your name"
Lua:
local name = "Dan"
local _exp_0 = name
if "Robert" == _exp_0 then
print("You are Robert")
elseif "Dan" == _exp_0 or "Daniel" == _exp_0 then
print("Your name, it's Dan")
else
print("I don't know about your name")
end
A switch when clause can match against multiple values by listing them out comma separated.
Switches can be used as expressions as well, here we can assign the result of the switch to a variable:
MoonScript:
b = 1
next_number = switch b
when 1
2
when 2
3
else
error "can't count that high!"
Lua:
local b = 1
local next_number
local _exp_0 = b
if 1 == _exp_0 then
next_number = 2
elseif 2 == _exp_0 then
next_number = 3
else
next_number = error("can't count that high!")
end
We can use the then keyword to write a switch’s when block on a single line. No extra keyword is needed to write the else block on a single line.
MoonScript:
msg = switch math.random(1, 5)
when 1 then "you are lucky"
when 2 then "you are almost lucky"
else "not so lucky"
Lua:
local msg
local _exp_0 = math.random(1, 5)
if 1 == _exp_0 then
msg = "you are lucky"
elseif 2 == _exp_0 then
msg = "you are almost lucky"
else
msg = "not so lucky"
end
It is worth noting the order of the case comparison expression. The case’s expression is on the left hand side. This can be useful if the case’s expression wants to overwrite how the comparison is done by defining an eq metamethod.