Skip to main content

UserData

Derive Macro UserData 

Source
#[derive(UserData)]
{
    // Attributes available to this derive:
    #[field]
}
Expand description

Generates a [mlua::UserData] implementation from struct fields.

Each named and unnamed field is automatically exposed to Lua as a read and/or write property or index.

Use #[field(...)] attributes to controll access and naming:

  • readonly: Set the field to only be readable within Lua
  • writeonly: Set the field to only be writable within Lua
  • skip: Ignore generating and exposing the field
  • rename: Rename the field to a string for a named field and a digit for an indexed field

Note: readonly + writeonly together is the same as having neither, the field will be exposed for both read and write.

Optionally combine with user_data_impl to also register methods in a rust like manner.

§Example

#[derive(Clone, UserData)]
struct Player {
    name: String,
    health: f64,
    #[field(skip)]
    handle: u64,
    #[field(readonly)]
    score: i32,
    #[field(rename = "pos_x")]
    position_x: f64,
}
#[derive(Clone, UserData)]
enum PlayerAction {
    Idle,
    Move {
        x: i32,
        y: i32
    },
    Attack(
        #[field(rename = "name")]
        String
    ),
    Quit,
}