Trait UserData

Source
pub trait UserData: Sized {
    // Provided methods
    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { ... }
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { ... }
    fn register(registry: &mut UserDataRegistry<Self>) { ... }
}
Expand description

Trait for custom userdata types.

By implementing this trait, a struct becomes eligible for use inside Lua code.

Implementation of IntoLua is automatically provided, FromLua needs to be implemented manually.

§Examples

struct MyUserData;

impl UserData for MyUserData {}

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

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<F: UserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("val", |_, this| Ok(this.0));
    }

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

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

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

lua.load(r#"
    assert(myobject.val == 123)
    myobject:add(7)
    assert(myobject.val == 130)
    assert(myobject + 10 == 140)
"#).exec()?;

Provided Methods§

Source

fn add_fields<F: UserDataFields<Self>>(fields: &mut F)

Adds custom fields specific to this userdata.

Source

fn add_methods<M: UserDataMethods<Self>>(methods: &mut M)

Adds custom methods and operators specific to this userdata.

Source

fn register(registry: &mut UserDataRegistry<Self>)

Registers this type for use in Lua.

This method is responsible for calling add_fields and add_methods on the provided UserDataRegistry.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§