diff --git a/src/runner/runner.rs b/src/runner/runner.rs index e70fb37..80efe97 100644 --- a/src/runner/runner.rs +++ b/src/runner/runner.rs @@ -1,4 +1,5 @@ use crate::context::Context; +use crate::scheduler::scheduler_mut; pub struct Runner{ lua:mlua::Lua, @@ -29,6 +30,7 @@ fn init(lua:&mlua::Lua)->mlua::Result<()>{ //global environment let globals=lua.globals(); + crate::scheduler::set_globals(lua,&globals)?; super::r#enum::set_globals(lua,&globals)?; super::color3::set_globals(lua,&globals)?; super::vector3::set_globals(lua,&globals)?; diff --git a/src/scheduler.rs b/src/scheduler.rs index f99a5c8..05b4d8a 100644 --- a/src/scheduler.rs +++ b/src/scheduler.rs @@ -56,3 +56,44 @@ impl Scheduler{ self.schedule.remove(&self.tick) } } + +fn coerce_float64(value:&mlua::Value)->Option{ + match value{ + &mlua::Value::Integer(i)=>Some(i as f64), + &mlua::Value::Number(f)=>Some(f), + _=>None, + } +} +pub fn scheduler_mut(lua:&mlua::Lua,mut f:impl FnMut(&mut crate::scheduler::Scheduler)->mlua::Result)->mlua::Result{ + let mut scheduler=lua.app_data_mut::().ok_or(mlua::Error::runtime("Scheduler missing"))?; + f(&mut *scheduler) +} +pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table)->Result<(),mlua::Error>{ + let schedule_thread=lua.create_function(move|lua,dt:mlua::Value|{ + let delay=coerce_float64(&dt).ok_or(mlua::Error::runtime("Expected float"))?.max(0.0)*60.0; + if delay("coroutine")?)?; + wait_env.raw_set("schedule_thread",schedule_thread)?; + let wait=lua.load(" + local coroutine_yield=coroutine.yield + local schedule_thread=schedule_thread + return function(dt) + schedule_thread(dt) + return coroutine_yield() + end + ") + .set_name("wait") + .set_environment(wait_env) + .call::(())?; + globals.raw_set("wait",wait)?; + + Ok(()) +}