specialize coerce f64 code

This commit is contained in:
Quaternions 2024-10-16 23:07:32 -07:00
parent 135103364d
commit f8f659e8ce

View File

@ -57,27 +57,33 @@ impl Scheduler{
}
}
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();
let schedule_thread=lua.create_function(|lua,dt:mlua::Value|{
let delay=match dt{
mlua::Value::Integer(i)=>i.max(0) as u64*60,
mlua::Value::Number(f)=>{
let delay=f.max(0.0)*60.0;
match delay.classify(){
std::num::FpCategory::Nan=>Err(mlua::Error::runtime("NaN"))?,
std::num::FpCategory::Infinite=>return Ok(()),
std::num::FpCategory::Normal=>if (u64::MAX as f64)<delay{
return Ok(());
},
_=>(),
}
delay as u64
},
mlua::Value::Nil=>0,
_=>Err(mlua::Error::runtime("Expected float"))?,
};
scheduler_mut(lua,|scheduler|{
scheduler.schedule_thread(delay.max(2),lua.current_thread());
Ok(())
})
})?;
let wait_env=lua.create_table()?;
wait_env.raw_set("coroutine",globals.get::<mlua::Table>("coroutine")?)?;