This commit is contained in:
Quaternions 2024-10-16 17:45:41 -07:00
parent 752ad6bd95
commit 9c1807ec76
2 changed files with 43 additions and 0 deletions

View File

@ -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)?;

View File

@ -56,3 +56,44 @@ impl Scheduler{
self.schedule.remove(&self.tick)
}
}
fn coerce_float64(value:&mlua::Value)->Option<f64>{
match value{
&mlua::Value::Integer(i)=>Some(i as f64),
&mlua::Value::Number(f)=>Some(f),
_=>None,
}
}
pub fn scheduler_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut crate::scheduler::Scheduler)->mlua::Result<T>)->mlua::Result<T>{
let mut scheduler=lua.app_data_mut::<crate::scheduler::Scheduler>().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<u64::MAX as f64{
scheduler_mut(lua,|scheduler|{
scheduler.schedule_thread((delay as u64).max(2),lua.current_thread());
Ok(())
}).unwrap();
}
Ok(())
})?;
let wait_env=lua.create_table()?;
wait_env.raw_set("coroutine",globals.get::<mlua::Table>("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::<mlua::Function>(())?;
globals.raw_set("wait",wait)?;
Ok(())
}