Skip to content

How to implement a select for Lua? #375

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

You must be logged in to vote

It's possible, eg. you can use futures_util::future::select_ok helper:

    let sleep = LuaFunction::wrap_async(|_, secs: f64| async move {
        tokio::time::sleep(tokio::time::Duration::from_secs_f64(secs)).await;
        Ok(secs)
    });
    let select = LuaFunction::wrap_async(|_, futs: Variadic<LuaFunction>| async move {
        let (res, _) = futures_util::future::select_ok(
            futs.into_iter()
                .map(|f| Box::pin(f.call_async::<_, LuaValue>(()))),
        )
        .await?;
        Ok(res)
    });

    lua.load(mlua::chunk! {
        local res = $select(function() return $sleep(0.1) end, function() return $sleep(0.2) end)
        print(res)
    }).exec_async().

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@sxyazi
Comment options

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