This commit is contained in:
Quaternions 2024-10-16 17:45:41 -07:00
parent 6de3f0c0d5
commit 6f12c20e36

View File

@ -23,12 +23,49 @@ impl std::fmt::Display for Error{
}
impl std::error::Error for Error{}
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,
}
}
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)
}
fn init(lua:&mlua::Lua)->mlua::Result<()>{
lua.sandbox(true)?;
//global environment
let globals=lua.globals();
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)?;
super::r#enum::set_globals(lua,&globals)?;
super::color3::set_globals(lua,&globals)?;
super::vector3::set_globals(lua,&globals)?;