2023-01-23 02:14:13 +00:00
|
|
|
use std::time::{Duration, Instant};
|
2023-01-21 18:33:33 +00:00
|
|
|
|
2023-01-23 02:31:55 +00:00
|
|
|
use mlua::prelude::*;
|
2023-01-23 02:14:13 +00:00
|
|
|
use smol::Timer;
|
2023-01-21 18:33:33 +00:00
|
|
|
|
2023-01-23 01:18:09 +00:00
|
|
|
use crate::utils::table_builder::TableBuilder;
|
2023-01-21 20:48:56 +00:00
|
|
|
|
2023-01-23 04:00:09 +00:00
|
|
|
const TASK_LIB: &str = include_str!("../luau/task.luau");
|
|
|
|
|
2023-01-23 02:31:55 +00:00
|
|
|
pub async fn create(lua: &Lua) -> LuaResult<()> {
|
2023-01-23 04:00:09 +00:00
|
|
|
let wait = lua.create_async_function(move |_, duration: Option<f32>| async move {
|
|
|
|
let start = Instant::now();
|
|
|
|
Timer::after(
|
|
|
|
duration
|
|
|
|
.map(Duration::from_secs_f32)
|
|
|
|
.unwrap_or(Duration::ZERO),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let end = Instant::now();
|
|
|
|
Ok((end - start).as_secs_f32())
|
|
|
|
})?;
|
|
|
|
let task_lib: LuaTable = lua
|
|
|
|
.load(TASK_LIB)
|
|
|
|
.set_name("task")?
|
|
|
|
.call_async(wait.clone())
|
|
|
|
.await?;
|
2023-01-22 20:23:56 +00:00
|
|
|
lua.globals().raw_set(
|
|
|
|
"task",
|
2023-01-23 01:18:09 +00:00
|
|
|
TableBuilder::new(lua)?
|
2023-01-23 04:00:09 +00:00
|
|
|
.with_value("cancel", task_lib.raw_get::<_, LuaFunction>("cancel")?)?
|
|
|
|
.with_value("defer", task_lib.raw_get::<_, LuaFunction>("defer")?)?
|
|
|
|
.with_value("delay", task_lib.raw_get::<_, LuaFunction>("delay")?)?
|
|
|
|
.with_value("spawn", task_lib.raw_get::<_, LuaFunction>("spawn")?)?
|
|
|
|
.with_value("wait", wait)?
|
2023-01-23 01:18:09 +00:00
|
|
|
.build_readonly()?,
|
2023-01-22 21:26:45 +00:00
|
|
|
)
|
|
|
|
}
|