rhai/scripts/switch.rhai

23 lines
780 B
JavaScript
Raw Permalink Normal View History

2022-07-24 23:03:35 +08:00
//! This script runs a switch statement in a for-loop.
2022-01-20 12:06:36 +08:00
2021-12-20 15:18:44 +08:00
let arr = [42, 123.456, "hello", true, "hey", 'x', 999, 1, 2, 3, 4];
2021-06-07 20:15:06 +08:00
for item in arr {
switch item {
2022-01-20 12:06:36 +08:00
// Match single integer
2021-06-07 20:15:06 +08:00
42 => print("The Answer!"),
2022-01-20 12:06:36 +08:00
// Match single floating-point number
2021-06-07 20:15:06 +08:00
123.456 => print(`Floating point... ${item}`),
2022-01-20 12:06:36 +08:00
// Match single string
2021-06-07 20:15:06 +08:00
"hello" => print(`${item} world!`),
2022-01-20 12:06:36 +08:00
// Match another integer
2021-12-20 15:18:44 +08:00
999 => print(`Got 999: ${item}`),
2022-01-20 12:06:36 +08:00
// Match range with condition
2021-12-20 15:18:44 +08:00
0..100 if item % 2 == 0 => print(`A small even number: ${item}`),
2022-01-20 12:06:36 +08:00
// Match another range
2021-12-20 15:18:44 +08:00
0..100 => print(`A small odd number: ${item}`),
2022-01-20 12:06:36 +08:00
// Default case
2021-12-20 15:18:44 +08:00
_ => print(`Something else: <${item}> is ${type_of(item)}`)
2021-06-07 20:15:06 +08:00
}
}