Trait mlua::UserData[][src]

pub trait UserData: Sized {
    fn add_fields<'lua, F: UserDataFields<'lua, Self>>(_fields: &mut F) { ... }
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(_methods: &mut M) { ... } }
Expand description

Trait for custom userdata types.

By implementing this trait, a struct becomes eligible for use inside Lua code. Implementations of ToLua and FromLua are automatically provided.


struct MyUserData(i32);

impl UserData for MyUserData {}

// `MyUserData` now implements `ToLua`:
lua.globals().set("myobject", MyUserData(123))?;

lua.load("assert(type(myobject) == 'userdata')").exec()?;

Custom fields, methods and operators can be provided by implementing add_fields or add_methods (refer to UserDataFields and UserDataMethods for more information):

struct MyUserData(i32);

impl UserData for MyUserData {
    fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
        fields.add_field_method_get("val", |_, this| Ok(this.0));

    fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_method_mut("add", |_, this, value: i32| {
            this.0 += value;

        methods.add_meta_method(MetaMethod::Add, |_, this, value: i32| {
            Ok(this.0 + value)

lua.globals().set("myobject", MyUserData(123))?;

    assert(myobject.val == 123)
    assert(myobject.val == 130)
    assert(myobject + 10 == 140)

Provided methods

Adds custom fields specific to this userdata.

Adds custom methods and operators specific to this userdata.

Implementations on Foreign Types