Skip to content

Commit f7a9324

Browse files
committed
switch docs
1 parent 3f6c1d5 commit f7a9324

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/reference.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,47 @@ And with basic loops:
486486

487487
print "item: ", item for item in *items
488488

489+
## Switch
490+
491+
The switch statement is shorthand for writing a series of if statements that
492+
check against the same value. Note that the value is only evaluated once. Like
493+
if statements, switches can have an else block to handle no matches. Comparison
494+
is done with the `==` operator.
495+
496+
name = "Dan"
497+
switch name
498+
case "Robert"
499+
print "You are robert"
500+
case "Dan"
501+
print "Your name, it's Dan"
502+
else
503+
print "I don't know about your name"
504+
505+
Switches can be used as expressions as well, here we can assign the result of
506+
the switch to a variable:
507+
508+
b = 1
509+
next_number = switch b
510+
case 1
511+
2
512+
case 2
513+
3
514+
else
515+
error "can't count that high!"
516+
517+
We can use the `then` keyword to write a switch case's block on a single line.
518+
No extra keyword is needed to write the else block on a single line.
519+
520+
msg = switch math.random(1, 5)
521+
case 1 then "you are lucky"
522+
case 2 then "you are almost lucky"
523+
else "not so lucky"
524+
525+
It is worth noting the order of the case comparison expression. The case's
526+
expression is on the left hand side. This can be useful if the case's
527+
expression wants to overwrite how the comparison is done by defining an `eq`
528+
metamethod.
529+
489530
## Object Oriented Programming
490531

491532
In these examples, the generated Lua code may appear overwhelming. It is best

0 commit comments

Comments
 (0)