#luau #scheduler #async #async-io

mlua-luau-scheduler

基于Luau的异步调度器,使用mlua和async-executor

2个版本

0.0.2 2024年3月11日
0.0.1 2024年2月16日

#367 in 异步

Download history 327/week @ 2024-03-11 40/week @ 2024-03-18 59/week @ 2024-03-25 115/week @ 2024-04-01 143/week @ 2024-04-08 402/week @ 2024-04-15 70/week @ 2024-04-22 77/week @ 2024-04-29 185/week @ 2024-05-06 75/week @ 2024-05-13 43/week @ 2024-05-20 95/week @ 2024-05-27 79/week @ 2024-06-03 77/week @ 2024-06-10 80/week @ 2024-06-17 38/week @ 2024-06-24

每月282次下载
8 个crate中使用 (7个直接使用)

MPL-2.0 许可证

59KB
1K SLoC

mlua-luau-scheduler


Luau的异步调度器,使用 mlua,并构建在 async-executor 之上。

该crate是运行时无关的,与任何异步运行时兼容,包括 Tokiosmolasync-std 等。
但是,由于许多依赖与 smol 共享,可能更倾向于使用它而不是其他运行时。

示例用法

1. 导入依赖项

use std::time::{Duration, Instant};
use std::io::ErrorKind;

use async_io::{block_on, Timer};
use async_fs::read_to_string;

use mlua::prelude::*;
use mlua_luau_scheduler::*;

2. 设置Lua环境

let lua = Lua::new();

lua.globals().set(
    "sleep",
    lua.create_async_function(|_, duration: f64| async move {
        let before = Instant::now();
        let after = Timer::after(Duration::from_secs_f64(duration)).await;
        Ok((after - before).as_secs_f64())
    })?,
)?;

lua.globals().set(
    "readFile",
    lua.create_async_function(|lua, path: String| async move {
        // Spawn background task that does not take up resources on the lua thread
        // Normally, futures in mlua can not be shared across threads, but this can
        let task = lua.spawn(async move {
            match read_to_string(path).await {
                Ok(s) => Ok(Some(s)),
                Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
                Err(e) => Err(e),
            }
        });
        task.await.into_lua_err()
    })?,
)?;

3. 设置调度器,运行线程

let sched = Scheduler::new(&lua)?;

// We can create multiple lua threads ...
let sleepThread = lua.load("sleep(0.1)");
let fileThread = lua.load("readFile(\"Cargo.toml\")");

// ... spawn them both onto the scheduler ...
sched.push_thread_front(sleepThread, ());
sched.push_thread_front(fileThread, ());

// ... and run until they finish
block_on(sched.run());

依赖项

~4–11MB
~102K SLoC