Skip to content

How to call an async function in a callback style? #612

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

You must be logged in to vote

You don't need to create LocalSet inside function, you can create it once, enter and use everywhere through task::spawn_local.

#[tokio::main]
async fn main() -> Result<()> {
    let local_set = tokio::task::LocalSet::new();
    let _guard = local_set.enter();
    let lua = Lua::new();

    let globals = lua.globals();

    globals.set(
        "some_work",
        lua.create_async_function(|_, ()| async move {
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            Ok("Slept for 1 second".to_owned())
        })?,
    )?;

    globals.set(
        "await",
        lua.create_function(|_, (f, cb): (Function, Function)| {
            tokio::task::spawn_local(async 

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@sxyazi
Comment options

@khvzak
Comment options

@sxyazi
Comment options

@khvzak
Comment options

Answer selected by sxyazi
@sxyazi
Comment options

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