Skip to content

Is it possible to create an object-safe userdata trait? #335

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

You must be logged in to vote

It's a bit non-trivial, but you can add proxying __index metatamethod to Box<dyn Object> to forward requests to target imlementation.
Something like this:

pub trait Object {
    fn print(&self);

    fn call_method<'l>(&self, lua: &'l Lua, name: &str, args: MultiValue<'l>) -> LuaResult<MultiValue<'l>>;
}

impl UserData for Box<dyn Object> {
    fn add_methods<'lua, M: mlua::prelude::LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_meta_function(MetaMethod::Index, |lua, (_, name): (AnyUserData, String)| {
            lua.create_function(move |lua, (this, args): (UserDataRef<Self>, MultiValue)| {
                this.call_method(lua, &name, args)
            })
        })

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@Dark42ed
Comment options

@khvzak
Comment options

Answer selected by Dark42ed
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