pub trait UserData: Sized {
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 {}
let lua = Lua::new();
// `MyUserData` now implements `ToLua`:
lua.globals().set("myobject", MyUserData(123))?;
lua.exec::<_, ()>("assert(type(myobject) == 'userdata')", None)?;
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)
});
}
}
let lua = Lua::new();
lua.globals().set("myobject", MyUserData(123))?;
lua.exec::<_, ()>(r#"
assert(myobject:get() == 123)
myobject:add(7)
assert(myobject:get() == 130)
assert(myobject + 10 == 140)
"#, None)?;
Provided Methods
sourcefn add_methods<'lua, T>(_methods: &mut T)where
T: UserDataMethods<'lua, Self>,
fn add_methods<'lua, T>(_methods: &mut T)where
T: UserDataMethods<'lua, Self>,
Adds custom methods and operators specific to this userdata.