| 1 | = Branch = |
| 2 | |
| 3 | The branch statement is used to conditionally execute code where there are a range of execution options on a single variable value. |
| 4 | |
| 5 | == Grammar == |
| 6 | {{{ |
| 7 | branch <variable> |
| 8 | on <value> [or <value>]... |
| 9 | <statements> |
| 10 | [on <value> [or <value>]... |
| 11 | <statements> ]... |
| 12 | [else |
| 13 | <statements>] |
| 14 | |
| 15 | branch <variable> |
| 16 | on <value>, <statement> |
| 17 | on <value>, <statement> |
| 18 | [else, <statement>] |
| 19 | }}} |
| 20 | The value of variable is evaluated and the '''on''' clause matching the value is evaluated. |
| 21 | If there is no match any '''else''' clause is evaluated |
| 22 | |
| 23 | * What's being branched on must be an integer, character, enumeration or string. |
| 24 | * The expressions being matched ( the <value>s ) must be constants (e.g. 0, 1, c'x', State.Off, "foo"). |
| 25 | |
| 26 | The second form is for one line statements and allows the '''on''' value and statement to be on the same line. |
| 27 | Multiple matching values can be specified separated by keyword '''or''' |
| 28 | |
| 29 | == Examples == |
| 30 | {{{ |
| 31 | # Notice the keywords `branch` and |
| 32 | # `on` as well as the indentation under each `on` clause |
| 33 | x = 2 |
| 34 | branch x |
| 35 | on 1 |
| 36 | isEven = false |
| 37 | word = 'one' |
| 38 | on 2 |
| 39 | isEven = true |
| 40 | word = 'two' |
| 41 | on 3 |
| 42 | isEven = false |
| 43 | word = 'three' |
| 44 | else |
| 45 | word='UNKNOWN' |
| 46 | assert isEven |
| 47 | assert word == 'two' |
| 48 | }}} |
| 49 | |
| 50 | |
| 51 | |
| 52 | If there is only one statement for the `on` or `else` and you want to tighten up your code, you can do so by using a comma (,) after the 'on' clause |
| 53 | and putting the statement on the same line |
| 54 | {{{ |
| 55 | x = 'toof' |
| 56 | branch x |
| 57 | on 'woof', word = 'one' |
| 58 | on 'doof', word = 'three' |
| 59 | else, word = 'else' |
| 60 | assert word == 'else' |
| 61 | }}} |
| 62 | |
| 63 | You can have more than one value for a single `on` clause |
| 64 | {{{ |
| 65 | x = 2 |
| 66 | branch x |
| 67 | on 1 or 2 or 3, word = 'number' |
| 68 | else, word = 'else' |
| 69 | assert word == 'number' |
| 70 | }}} |