Skip to main content

ScriptEnum

Derive Macro ScriptEnum 

Source
#[derive(ScriptEnum)]
Expand description

Derive macro ScriptEnum. Enables a Rust enum to be used in a ‘C’ like mannner within the tinyscript language.

The variants are numbered like Rust does: from 0, or continuing from an explicit discriminant. Explicit discriminants must be integer literals that fit into an i8, negative ones included, e.g. -3; the variants must have no fields.

§Usage

#[derive(ScriptEnum)]
enum Color {
    Red,
    Green = 5,
    Blue,
}

// make the variants known to the scripts
for (name, discriminant) in Color::key_value_tuples() {
    runtime.register_enum_tuple(name, discriminant)?;
}

§Result

Expands the above enum to

enum Color {
    Red,
    Green = 5,
    Blue,
}

#[automatically_derived]
#[diagnostic::do_not_recommend]
impl tinyscript::ScriptEnum for Color {
    fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
        tinyscript::__private::vec![("Red", 0), ("Green", 5), ("Blue", 6)]
    }
}

§Errors

Compilation errors, pointing at the cause:

  • if used on structs or unions
  • if a variant has fields
  • if a discriminant is not an integer literal or does not fit into an i8
  • if an implicit discriminant would exceed i8::MAX