-
Ok so, I have one pub struct HttpRequest {
request: Request<Body>,
headers: Headers,
}
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If I correctly understand question, you cannot simply return reference to an internal field from a metamethod, unfortunately. For example: use mlua::{chunk, Lua, MetaMethod, Result, UserData, UserDataFields, UserDataMethods};
#[derive(Clone)]
struct Headers(Arc<Mutex<HashMap<String, String>>>);
pub struct HttpRequest {
request: Request<Body>,
headers: Headers,
}
impl UserData for HttpRequest {
fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_field_method_get("headers", |_, this| Ok(this.headers.clone()));
}
}
impl UserData for Headers {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::Index, |_, this, name: String| {
Ok(this.0.lock().unwrap().get(&name).cloned())
});
methods.add_meta_method_mut(
MetaMethod::NewIndex,
|_, this, (name, value): (String, String)| {
this.0.lock().unwrap().insert(name, value);
Ok(())
},
);
}
} (valid for mlua |
Beta Was this translation helpful? Give feedback.
If I correctly understand question, you cannot simply return reference to an internal field from a metamethod, unfortunately.
The easiest way is to wrap
Headers
toArc<Mutex< Headers >>
and return a copy instead.For example: