structure

Attribute Macro structure 

Source
#[structure]
Expand description

Implements a helper function _to_mlua_fields for a Rust struct, enabling automatic registration of named fields with mlua::UserData.

When applied to a struct, this macro generates an implementation of a private helper function that is later invoked by the mlua_magic_macros::compile! macro. This ensures the struct’s fields are visible in Lua as userdata fields.

§Behavior

  • Public and private named fields are exported as readable fields in Lua.
  • Getter methods are automatically generated via add_field_method_get.
  • Fields must implement Clone for successful conversion to Lua values.

§Limitations

  • Only structs with named fields are currently supported.
  • Setter support is not yet implemented.

§Usage

Apply the macro directly to the struct definition:

#[derive(Clone, Copy, Default)]
#[mlua_magic_macros::structure]
struct Player {
    name: String,
    hp: i32,
}

// Later, compile userdata:
mlua_magic_macros::compile!(Player, fields, methods);

After registration through mlua::UserData, Lua scripts may access the fields:

print(player.name)
print(player.hp)

This macro is designed to work together with:

  • #[mlua_magic_macros::implementation] — for methods
  • #[mlua_magic_macros::enumeration] — for enum variants
  • mlua_magic_macros::compile! — final hookup to mlua::UserData

This simplifies mlua integration by reducing boilerplate and ensuring a consistent interface between Rust types and Lua scripts.