Match
A match expression branches on a pattern.
Match expressions must be exhaustive, meaning that every possible
pattern must be matched, i.e., have an arm handling it. The catch all
arm (_), which matches any value, can be used to do this.
Match expressions also ensure that all of the left-sided arms match the same type of the scrutinee expression, and the right-sided arms are all of the same type.
local word = match "hello" {
["hello"] = "hi",
["bonjour"] = "salut",
["hola"] = "hola",
_ = "<unknown>",
}
assert(word == "hi")
Functions
match
Match.match(value: T--
The value to match on
) → matcherArms<T,U>--
A matcher function to call with the match arms
A match expression branches on a pattern. A match expression has a scrutinee expression (the value to match on) and a list of patterns.
NOTE
Currently, most traditional pattern matching is not supported, with
the exception of the catch all pattern (_).
A common use-case of match is to prevent repetitive if statements, when
checking against various possible values of a variable:
local function getGreetingNumber(greeting: string): number
return match(greeting) {
["hello, world"] = 1,
["hello, mom"] = 2,
_ = function(val)
return #val
end,
}
end
assert(getGreetingNumber("hello, world") == 1)
assert(getGreetingNumber("hello, mom") == 2)
assert(getGreetingNumber("hello, john") == 11)