switch statements
Gosu evaluates the switch expression, and uses the result to choose one course of action from a set
of multiple choices. Gosu evaluates the expression, and then iterates through the case expressions in order until
it finds a match.
- If a case value equals the expression, Gosu executes its accompanying statement list. Statement
execution continues until Gosu encounters a
breakstatement, or the switch statement ends. Gosu continues to the next case and executes multiple case sections if you omit thebreakstatement. - If no case
value equals the expression, Gosu skips to the default case, if one exists. The default case is a case section
with the label
default:rather thancaseVALUE:. The default case must be the last case in the list of sections.
The switch statement block uses a multi-part construction. The default statement is
optional. In most cases, you implement a default case to handle any unexpected conditions.
Syntax
switch (<expression>) {
case label1 :
[statementlist1]
[break]
[ ...
[ case labelN :
[statementlistN]
[break] ] ]
[ default :
[statementlistDefault]]
}Example
switch (strDigitName) {
case "one":
strOrdinalName = "first"
break
case "two":
strOrdinalName = "second"
break
case "three":
strOrdinalName = "third"
break
case "five":
strOrdinalName = "fifth"
break
case "eight":
strOrdinalName = "eighth"
break
case "nine":
strOrdinalName = "ninth"
break
default:
strOrdinalName = strDigitName + "th"
}
To improve the readability of your Gosu code, Gosu
automatically downcasts the object after a typeis expression if the type
is a subtype of the original type. This is particularly valuable for
if statements and similar
Gosu structures such as switch.
Within the Gosu code bounded by the if
or switch statement, you
do not need to do casting (as TYPE expressions) to
that subtype for that case. Because Gosu confirms that the object has
the more specific subtype, Gosu implicitly considers that variable’s
type to be the subtype for that block of code. There are several special
cases that turn off the downcasting.
See also
