How to return a different data type in same UserData's methods
blame2020 opened this issue · 3 comments
In typically, '==' returns a bool. and '+' returns same type as l/r value.
But it looks like no such implementation is possible because add_methods can only return the same type.
Any ideas to solve this problem?
impl rlua::UserData for XXX {
fn add_methods<'lua, M: rlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(rlua::MetaMethod::ToString, |_, this, _: ()| {
Ok(Self(...))
});
methods.add_meta_method::<'lua, bool>(rlua::MetaMethod::Eq, |_, this, value: Decimal| {
Ok(bool) // NG
});
}
}
Hi,
Can you be more specific about what you're trying to do and how it is going wrong?
For example this works:
use rlua;
#[derive(Clone)]
struct MyType(String);
impl rlua::UserData for MyType {
fn add_methods<'lua, M: rlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(rlua::MetaMethod::Add, |_, this, other: MyType| {
Ok("some string")
});
methods.add_meta_method(rlua::MetaMethod::ToString, |_, this, _: ()| {
Ok(this.0.clone())
});
}
}
fn main() -> rlua::Result<()> {
let lua = rlua::Lua::new();
lua.context(|lua_ctx| {
let globals = lua_ctx.globals();
globals.set("x", MyType("xx".into()))?;
globals.set("y", MyType("yy".into()))?;
lua_ctx.load(r#"
print(x)
print(y)
print(x+y)
"#).exec()?;
Ok(())
})?;
Ok(())
}
The Add
metamethod above returns a plain string instead of the type of the userdata argument.
Note that there are some restrictions - for example the result of the comparison operators (including ==
) is always converted to bool
, but that's a feature of Lua itself and not imposed by rlua.
I'm sorry.
It was a misunderstanding.
Thanks to you, I was able to organize it.
The "Ok (bool)" part was actually written as "Ok (Self (true))".
I was able to do what I wanted to do.
Nothing to be sorry about! And glad you've solved your problem.