Trait rlua::UserData[][src]

pub trait UserData: 'static + Sized {
    fn add_methods(_methods: &mut UserDataMethods<Self>) { ... }
}

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(methods: &mut UserDataMethods<Self>) {
        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

Adds custom methods and operators specific to this userdata.

Implementors