2023-01-21 18:33:33 +00:00
|
|
|
use std::time::Duration;
|
|
|
|
|
2023-01-21 20:30:22 +00:00
|
|
|
use mlua::{Function, Lua, Result, Table, Value, Variadic};
|
2023-01-21 18:33:33 +00:00
|
|
|
use tokio::time;
|
|
|
|
|
|
|
|
const DEFAULT_SLEEP_DURATION: f32 = 1.0 / 60.0;
|
|
|
|
|
2023-01-21 20:30:22 +00:00
|
|
|
pub fn new(lua: &Lua) -> Result<Table> {
|
|
|
|
let tab = lua.create_table()?;
|
|
|
|
tab.raw_set(
|
|
|
|
"defer",
|
|
|
|
lua.create_async_function(
|
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:30:22 +00:00
|
|
|
)?,
|
|
|
|
)?;
|
|
|
|
tab.raw_set(
|
|
|
|
"delay",
|
|
|
|
lua.create_async_function(
|
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:30:22 +00:00
|
|
|
)?,
|
|
|
|
)?;
|
|
|
|
tab.raw_set(
|
|
|
|
"spawn",
|
|
|
|
lua.create_async_function(
|
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:30:22 +00:00
|
|
|
)?,
|
|
|
|
)?;
|
|
|
|
tab.raw_set(
|
|
|
|
"wait",
|
|
|
|
lua.create_async_function(|_, 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:30:22 +00:00
|
|
|
})?,
|
|
|
|
)?;
|
|
|
|
tab.set_readonly(true);
|
|
|
|
Ok(tab)
|
2023-01-21 18:33:33 +00:00
|
|
|
}
|