lune/src/lib/globals/task.rs

57 lines
1.8 KiB
Rust
Raw Normal View History

use std::{
sync::{Arc, Mutex},
time::Duration,
};
2023-01-21 18:33:33 +00:00
use mlua::{Function, Lua, Result, Table, Thread, Value, Variadic};
2023-01-21 18:33:33 +00:00
use tokio::time;
use crate::utils::table_builder::ReadonlyTableBuilder;
2023-01-21 18:33:33 +00:00
const DEFAULT_SLEEP_DURATION: f32 = 1.0 / 60.0;
2023-01-21 22:02:49 +00:00
#[allow(dead_code)]
pub struct WaitingThread<'a> {
is_delayed_for: Option<f32>,
is_deferred: Option<bool>,
thread: Thread<'a>,
args: Variadic<Value<'a>>,
}
2023-01-21 22:02:49 +00:00
pub fn new<'a>(lua: &'a Lua, _threads: &Arc<Mutex<Vec<WaitingThread<'a>>>>) -> Result<Table<'a>> {
// TODO: Figure out how to insert into threads vec
ReadonlyTableBuilder::new(lua)?
.with_async_function(
"defer",
|lua, (func, args): (Function, Variadic<Value>)| async move {
let thread = lua.create_thread(func)?;
thread.into_async(args).await?;
Ok(())
},
)?
.with_async_function(
"delay",
|lua, (func, duration, args): (Function, Option<f32>, Variadic<Value>)| async move {
let secs = duration.unwrap_or(DEFAULT_SLEEP_DURATION);
time::sleep(Duration::from_secs_f32(secs)).await;
let thread = lua.create_thread(func)?;
thread.into_async(args).await?;
Ok(())
},
)?
.with_async_function(
"spawn",
2023-01-21 18:33:33 +00:00
|lua, (func, args): (Function, Variadic<Value>)| async move {
let thread = lua.create_thread(func)?;
thread.into_async(args).await?;
2023-01-21 18:33:33 +00:00
Ok(())
},
)?
.with_async_function("wait", |_, duration: Option<f32>| async move {
let secs = duration.unwrap_or(DEFAULT_SLEEP_DURATION);
time::sleep(Duration::from_secs_f32(secs)).await;
Ok(secs)
})?
.build()
2023-01-21 18:33:33 +00:00
}