Legato
Legato

GoFiler Legato Script Reference

 

Legato v 1.5d

Application v 5.25a

  

 

Chapter FourFlow Control (continued) 

4.9 The ‘switch’ Statement

4.9.1 Overview

The switch statement is a selection control mechanism used to allow the value of a variable or expression to change the flow of execution via a multiway branch. Switch statements are indicated by the switch keyword and the case keyword, which delineates the different cases and their associated blocks of statements. Switch statements are particularly useful when comparing a variable to a large set of possible values.

4.9.2 Syntax and Structure

The switch statements use the following formal syntax:

switch (expression)

case constant-expression:

statement(s)

[default:]

[statement(s)]

 

The expression is compared in each case to the constant-expression. If it evaluates to TRUE, the statement block associated with that case is executed. The following example demonstrates a switch statement.

      switch (day) {

case "Monday":

MessageBox("It's Monday. Time to start the week.");

break;

case "Friday":

MessageBox("It's Friday. Yay!");

break;

case "Saturday":

case "Sunday":

MessageBox("It's the weekend. Time to have fun.");

break;

default:

MessageBox("It's a weekday. Keep going!");

break;

        }

The previous example illustrates some important notes about switch statements. First, like C++, Legato features “fall through”, which means execution will continue with statements subsequent to the first case that evaluates as TRUE. The break keyword, which exits the switch block, must be used to prevent fall through if it is not desired. Similarly, multiple cases can be linked to the same statement block, such as is shown above with the cases “Saturday” and “Sunday”. Finally, the default case is a catchall statement if present. Much like the else statement, the default case is executed if no other case evaluates to TRUE.

A switch statement can resemble the action of multiple if else statements within an if block, and there are occasions where if else combinations make more sense as a programming structure. For more information on the if else statement, see Section 4.8 ‘if’, ‘elseif’ and ‘else’ Statements.

4.9.3 Limitations and Remarks

The switch only allows a base type integer and a string to be compared. The type of the switch statement and all of the case statements must match.

When comparing strings, it is always performed on a character for character exact match. The size is limited to 256 characters, if either string exceeds 256 characters, the comparison is truncated without warning. This effectively means that two strings, one that is 270 characters and one that is 500 character can match if the first 256 are the same.

Unlike many compiled languages featuring a switch type statement, the ‘case’ values need not be unique. The first match case is selected to be executed. Any duplicate cases are ignored.