Trait UserData

Source
pub trait UserData: Sized {
    // Provided method
    fn add_methods<'lua, T>(_methods: &mut T)
       where T: UserDataMethods<'lua, Self> { ... }
}
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.

§Examples

struct MyUserData(i32);

impl UserData for MyUserData {}

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

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

Custom methods and operators can be provided by implementing add_methods (refer to UserDataMethods for more information):

struct MyUserData(i32);

impl UserData for MyUserData {
    fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_method("get", |_, this, _: ()| {
            Ok(this.0)
        });

        methods.add_method_mut("add", |_, this, value: i32| {
            this.0 += value;
            Ok(())
        });

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

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

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

Provided Methods§

Source

fn add_methods<'lua, T>(_methods: &mut T)
where T: UserDataMethods<'lua, Self>,

Adds custom methods and operators specific to this userdata.

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§