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

set_hook doesn't work with async execution #347

Closed
b0bleet opened this issue Dec 24, 2023 · 2 comments
Closed

set_hook doesn't work with async execution #347

b0bleet opened this issue Dec 24, 2023 · 2 comments

Comments

@b0bleet
Copy link

b0bleet commented Dec 24, 2023

set_hook doesn't work properly when executing Lua with exec_async()

use anyhow::Result;
use mlua::{HookTriggers, Lua};

#[tokio::main]
async fn main() -> Result<()> {
    let lua = Lua::new();
    lua.set_hook(HookTriggers::EVERY_LINE, move |_lua, _debug| {
        println!("test hook");
        Ok(())
    });

    lua.load(
        r#"
            local x = 2 + 3
            local y = x * 63
            local z = string.len(x..", "..y)
        "#,
    )
    .exec_async()
    .await?;

    lua.remove_hook();

    Ok(())
}
@khvzak
Copy link
Member

khvzak commented Jan 6, 2024

It's not a bug, this is how Lua works.
Async execution happens in coroutines, and each coroutine need to have their own hook. Setting it in main Lua thread would only update the main thread without affecting others.

The correct code for hooks in async context would be:

async fn main() -> Result<()> {
    let lua = Lua::new();

    let func = lua
        .load(
            r#"
            local x = 2 + 3
            local y = x * 63
            local z = string.len(x..", "..y)
        "#,
        )
        .into_function()?;

    let thread = lua.create_thread(func)?;
    thread.set_hook(HookTriggers::EVERY_LINE, move |_lua, _debug| {
        println!("test hook 2");
        Ok(())
    });
    let _: () = thread.into_async(()).await?;

    lua.remove_hook();

    Ok(())
}

khvzak added a commit that referenced this issue Feb 7, 2025
- Support global hooks inherited by new threads
- Support thread hooks, where each thread can have its own hook

This should also allow to enable hooks for async calls.
Related to #489 #347
@khvzak
Copy link
Member

khvzak commented Feb 7, 2025

Fixed with global hooks

@khvzak khvzak closed this as completed Feb 7, 2025
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

Successfully merging a pull request may close this issue.

2 participants