2023-01-21 21:40:57 +00:00
|
|
|
use std::{
|
|
|
|
sync::{Arc, Mutex},
|
|
|
|
time::Duration,
|
|
|
|
};
|
2023-01-21 18:33:33 +00:00
|
|
|
|
2023-01-21 21:40:57 +00:00
|
|
|
use mlua::{Function, Lua, Result, Table, Thread, Value, Variadic};
|
2023-01-21 18:33:33 +00:00
|
|
|
use tokio::time;
|
|
|
|
|
2023-01-21 20:48:56 +00:00
|
|
|
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 21:40:57 +00:00
|
|
|
pub struct WaitingThread<'a> {
|
|
|
|
is_delayed_for: Option<f32>,
|
|
|
|
is_deferred: Option<bool>,
|
|
|
|
thread: Thread<'a>,
|
|
|
|
args: Variadic<Value<'a>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2023-01-21 20:48:56 +00:00
|
|
|
ReadonlyTableBuilder::new(lua)?
|
|
|
|
.with_async_function(
|
|
|
|
"defer",
|
2023-01-21 20:07:18 +00:00
|
|
|
|lua, (func, args): (Function, Variadic<Value>)| async move {
|
|
|
|
let thread = lua.create_thread(func)?;
|
|
|
|
thread.into_async(args).await?;
|
|
|
|
Ok(())
|
|
|
|
},
|
2023-01-21 20:48:56 +00:00
|
|
|
)?
|
|
|
|
.with_async_function(
|
|
|
|
"delay",
|
2023-01-21 20:07:18 +00:00
|
|
|
|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(())
|
|
|
|
},
|
2023-01-21 20:48:56 +00:00
|
|
|
)?
|
|
|
|
.with_async_function(
|
|
|
|
"spawn",
|
2023-01-21 18:33:33 +00:00
|
|
|
|lua, (func, args): (Function, Variadic<Value>)| async move {
|
2023-01-21 20:07:18 +00:00
|
|
|
let thread = lua.create_thread(func)?;
|
|
|
|
thread.into_async(args).await?;
|
2023-01-21 18:33:33 +00:00
|
|
|
Ok(())
|
|
|
|
},
|
2023-01-21 20:48:56 +00:00
|
|
|
)?
|
|
|
|
.with_async_function("wait", |_, duration: Option<f32>| async move {
|
2023-01-21 20:07:18 +00:00
|
|
|
let secs = duration.unwrap_or(DEFAULT_SLEEP_DURATION);
|
|
|
|
time::sleep(Duration::from_secs_f32(secs)).await;
|
|
|
|
Ok(secs)
|
2023-01-21 20:48:56 +00:00
|
|
|
})?
|
|
|
|
.build()
|
2023-01-21 18:33:33 +00:00
|
|
|
}
|