Is it possible for a UserData method to return a reference to this (self)? #357
-
I'm working on a configuration builder type of UserData, where every method call would ideally return the My UserData is something like this: pub struct MessageBuilder {
pub topic: Mutex<String>,
pub partition: Mutex<Option<i32>>,
}
impl UserData for MessageBuilder {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("partition", |lua, this, partition: i32| {
let mut locked_partition = this
.partition
.lock()
.map_err(|err| Error::RuntimeError(err.to_string()))?;
*locked_partition = Some(partition);
Ok(/* WHAT CAN GO HERE? */)
});
methods.add_method("topic", ...
} And I want to use it like this: local message = MessageBuilder:new():topic("topic"):partition(23):build() |
Beta Was this translation helpful? Give feedback.
Answered by
khvzak
Jan 14, 2024
Replies: 1 comment 1 reply
-
You need to use impl mlua::UserData for MessageBuilder {
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function("partition", |_, (ud, partition): (AnyUserData, _)| {
let mut this = ud.borrow_mut::<Self>()?;
this.partition = Some(partition);
Ok(ud)
});
}
} Also you don't really need to mutex to simply change struct fields, as can always borrow underlying data mutably. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
drauschenbach
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to use
add_function
which will receive userdata as first arg in form ofAnyUserData
to pass back.Also you don't really need to mutex to simply change struct fields, as can always borrow underlying data mutably.