Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to call async method of Arc<Mutex<T: UserData>> with userdata-wrappers feature? #511

Open
arkav opened this issue Jan 17, 2025 · 1 comment

Comments

@arkav
Copy link

arkav commented Jan 17, 2025

When migrating from version 0.9 I encountered the issue that when I try to call an async method of a Arc<Mutex<T>> of a type that implements UserData for example the following code returns an error.

impl UserData for SharedData {
    fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
        methods.add_async_method("some_async_method", |_, mut this, ()| async move {
            println!("Hello");
            tokio::time::sleep(Duration::from_secs(5)).await;
            println!("from the other side!");
            Ok(())
        });
    }
}

#[tokio::main]
async fn main() -> Result<(), mlua::Error> {
    let lua = Lua::new();

    lua.load(
        r#"
        function test(shared_data)
            shared_data:some_async_method()
        end
    "#,
    )
    .exec()?;

    let shared_data = Arc::new(Mutex::new(SharedData::new()));
    let func: mlua::Function = lua.globals().get("test")?;

    func.call_async::<()>(shared_data).await
}

The error returned:

Error: CallbackError { traceback: "stack traceback:\n\t[C]: in local 'poll'\n\t[string \"?\"]:4: in method 'some_async_method'\n\t[string \"src/main.rs:40:9\"]:3: in function 'test'", cause: BadArgument { to: Some("SharedData.some_async_method"), pos: 1, name: Some("self"), cause: UserDataTypeMismatch } }

Is this intended behavior?

@khvzak
Copy link
Member

khvzak commented Jan 19, 2025

This is not supported yet.
As a workaround you can change method to:

methods.add_async_function("some_async_method", |_, this: UserDataRef<Arc<Mutex<Self>>>| async move {
    println!("Hello");
    tokio::time::sleep(Duration::from_secs(1)).await;
    println!("from the other side!");
    Ok(())
});

Or receiving AnyUserData and then trying to borrow Self or Arc<Mutex<Self>> to support all cases.

I'll try to fix this in next version, it's not trivial unfortunately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants