11.13. Enumeration traits
The ENUM_TRAIT module provides reflection utilities for enumerations: iterating
over all values, converting between enum values and strings, and building
lookup tables. The [string_to_enum] annotation generates a string constructor
for the annotated enum type.
All functions and symbols are in “enum_trait” module, use require to get access to it.
require daslib/enum_trait
Example:
require daslib/enum_trait
enum Color {
red
green
blue
}
[export]
def main() {
print("{Color.green}\n")
let c = to_enum(type<Color>, "blue")
print("{c}\n")
let bad = to_enum(type<Color>, "purple", Color.red)
print("fallback = {bad}\n")
}
// output:
// green
// blue
// fallback = red
11.13.1. Typeinfo macros
- enum_names
Implements typeinfo(enum_names EnumOrEnumType) which returns array of strings with enumValue names.
- enum_length
Implements typeinfo(enum_length EnumOrEnumType) which returns total number of elements in enumeration.
11.13.2. Handled enumerations
- string_to_enum
Enumeration annotation which implements string constructor for enumeration.
11.13.3. Enumeration iteration
- each(tt: auto(TT)): iterator<TT>
Returns an iterator over all values of the given enumeration type.
- Arguments:
tt : auto(TT)
11.13.4. Enumeration conversion
- enum_to_table(ent: auto(EnumT)): table<string, EnumT>
- converts enum type to a table of name => value pairs
usage: let t = enum_to_table(type<EnumType>)
- Arguments:
ent : auto(EnumT)
- string(arg: auto): auto
- converts enum value to string
usage: let s = string(EnumValue)
- Arguments:
arg : auto
11.13.4.1. to_enum
- to_enum(ent: auto(EnumT); name: string): EnumT
- converts string to enum value, panics if not found
usage: let e = to_enum(type<EnumType>,”EnumValueName”)
- Arguments:
ent : auto(EnumT)
name : string
- to_enum(ent: auto(EnumT); name: string; defaultValue: EnumT): EnumT