saker.build
saker.build copied to clipboard
Switch expression in build script
Add syntax for switch expressions in build script.
One commonly occurring scenario is to assign some variable or perform some action based on the value of another variable. Currently this can be done using if-else statements:
$platform = # ...
if $platform == win32 {
# ...
} else if $platform == macos || $platform == ios {
# ...
} else {
abort("Unrecognized platform { $platform }")
}
This is harder to maintain as the variable name needs to be repeated and is uncomfortable to edit. This can be solved by introducing switch expressions.
switch $platform {
case win32 {
# ...
}
case macos, ios {
# ...
}
default {
abort("Unrecognized platform { $platform }")
}
}
There is no fallthrough between the case blocks. Multiple values to match for can be separated using a comma.
The statement basically checks the value of the subject for equality with each case label in order and executing the first one that matches.
The execution order is the following:
- Start the subject statement task and the labels all at once
- If the label declarations contain complex expressions, they will always be executed.
- With the value of the subject, check each label for equality
- Execute the first one that equals
- If no equal label is found, run the
default
branch if present.
Further improvements
The switch expression can also be improved to return a value. In this case the block may be omitted, and a returned value can be represented with a separator colon :
. Similarly to the foreach
expression:
$value = switch $platform {
case win32: 123
case macos, ios: 456
default: 999
}
It is not a syntactic error to not declare a return value for a given label, in that case the expression will return no-value that will result in an exception when its dereferenced.
The result value can be combined with blocks:
$value = switch $platform {
case win32 {
print("platform is win32")
}: 123
case macos, ios: 456
default {
abort("Unrecognized platform { $platform }")
}
}
Essentially both the block and result value are optional, but at least one of them must be present. (Similarly to foreach
)
No local variables can be declared for switch expression blocks. (As they don't run in a loop, target-level variables can be used.)