Trait me3_framework::scripting::lua::prelude::LuaUserData
source · [−]pub trait LuaUserData {
fn add_fields<'lua, F>(_fields: &mut F)
where
F: UserDataFields<'lua, Self>,
{ ... }
fn add_methods<'lua, M>(_methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{ ... }
}
Expand description
Trait for custom userdata types.
By implementing this trait, a struct becomes eligible for use inside Lua code.
Implementation of ToLua
is automatically provided, FromLua
is implemented
only for T: UserData + Clone
.
Examples
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;
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
sourcefn add_fields<'lua, F>(_fields: &mut F)where
F: UserDataFields<'lua, Self>,
fn add_fields<'lua, F>(_fields: &mut F)where
F: UserDataFields<'lua, Self>,
Adds custom fields specific to this userdata.
sourcefn add_methods<'lua, M>(_methods: &mut M)where
M: UserDataMethods<'lua, Self>,
fn add_methods<'lua, M>(_methods: &mut M)where
M: UserDataMethods<'lua, Self>,
Adds custom methods and operators specific to this userdata.