This example consists of a single file, LS/19.iss
This example demonstrates the use of a switch
to selectively execute one out of several possible code segments, called branches.
Enter the command run lern/ls/19
to run the example.
A switch
identifies a branch of code to execute based on a single provided value
. The statement itself looks like so:
switch value
A switch
is always followed by a block of braces {
and }
, each on its own line as is the LavishScript way. The switch
block is then filled with the possible branches of code to select from.
A case
statement specifies text
to directly compare the value
to. The comparison is a case-insensitive string compare. The statement itself looks like so:
case value
- Note: In many languages, a switch
case
value is numeric and/or followed by a:
(colon) as a matter of syntax. LavishScript treats the case value as verbatim text to compare, including any quotes or trailing colon.
If the value
matches the switch
line's, then code execution will continue immediately following the case
statement.
Code execution will then continue downward as usual, including any additional branches below! To skip past the end of the siwtch
, use a break
statement.
A typical switch
pattern with multiple case
s can therefore look like this:
switch ${ValueToCheck}
{
case value
echo value matched
break
case value1
case value2
echo value1 or value2 matched
break
}
A default
statement is used to specify a default branch to execute if no other branch was found to match the value specified by switch
A typical switch
pattern with a default
branch can look like this:
switch ${ValueToCheck}
{
case value1
break
case value2
break
default
echo No match!
break
}
A variablecase
statement can be used to provide dynamic branch values, which cannot be hard-coded into a typical case
statement.
Where a typical case
is intended for verbatim comparison, a variablecase
is expected to contain one or more Data Sequences that must first be resolved before comparison can be performed.
A variablecase
statement therefore typically looks something like this:
variablecase ${Value}
If no case
statement matched, then before the default
is selected, each specified variablecase
is then checked in order from top to bottom.
If a matching variablecase
is found, execution continues from below that variablecase
, the same way as is done for a case
or default
. Any further variablecase
lines are ignored, and their Data Sequences will not be resolved.
-
Add your own branch to the
switch
by adding acase
, anecho
, and abreak
. Run the script again, passing the value you specified on thecase
line as a parameter. -
Create your own .iss file with a
main
function that accepts astring
parameter, and aswitch
to selectively output something different if "On" or "Off" is passed as to the script. Usedefault
to detect that neither matched, and tell the user to provide On or Off!