Skip to content

pass reference to another UserData from the index of a UserData #50

Answered by khvzak
Absolucy asked this question in Q&A
Discussion options

You must be logged in to vote

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 to Arc<Mutex< Headers >> and return a copy instead.

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 a…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Absolucy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants