From bc9724e9de27d2df4c4b35903035b228d9242d59 Mon Sep 17 00:00:00 2001
From: Quaternions <krakow20@gmail.com>
Date: Wed, 16 Oct 2024 16:40:35 -0700
Subject: [PATCH] Scheduler lives in Lua

---
 src/runner/runner.rs | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/src/runner/runner.rs b/src/runner/runner.rs
index 78a4685..06815da 100644
--- a/src/runner/runner.rs
+++ b/src/runner/runner.rs
@@ -60,10 +60,10 @@ impl Runner{
 		}
 		//this makes set_app_data shut up about the lifetime
 		self.lua.set_app_data::<&'static mut rbx_dom_weak::WeakDom>(unsafe{core::mem::transmute(&mut context.dom)});
+		self.lua.set_app_data::<crate::scheduler::Scheduler>(crate::scheduler::Scheduler::default());
 		Ok(Runnable{
 			lua:self.lua,
 			_lifetime:&std::marker::PhantomData,
-			scheduler:crate::scheduler::Scheduler::default(),
 		})
 	}
 }
@@ -72,21 +72,16 @@ impl Runner{
 pub struct Runnable<'a>{
 	lua:mlua::Lua,
 	_lifetime:&'a std::marker::PhantomData<()>,
-	scheduler:crate::scheduler::Scheduler,
 }
 impl Runnable<'_>{
 	pub fn drop_context(self)->Runner{
 		self.lua.remove_app_data::<&'static mut rbx_dom_weak::WeakDom>();
+		self.lua.remove_app_data::<crate::scheduler::Scheduler>();
 		Runner{
 			lua:self.lua,
 		}
 	}
 	pub fn run_script(&self,script:super::instance::Instance)->Result<(),Error>{
-		let thread=self.make_script_thread(script)?;
-		thread.resume::<mlua::MultiValue>(()).map_err(|error|Error::Lua{source:"source not available".to_owned(),error})?;
-		Ok(())
-	}
-	pub fn make_script_thread(&self,script:super::instance::Instance)->Result<mlua::Thread,Error>{
 		let (name,source)=super::instance::get_name_source(&self.lua,script).map_err(Error::RustLua)?;
 		let fenv=self.lua.create_table().map_err(Error::RustLua)?;
 		//there's gotta be a more concise way to do this
@@ -99,6 +94,9 @@ impl Runnable<'_>{
 		.set_name(name).into_function().map_err(Error::RustLua)?;
 		f.set_environment(fenv).map_err(Error::RustLua)?;
 		let thread=self.lua.create_thread(f).map_err(Error::RustLua)?;
-		Ok(thread)
+		thread.resume::<mlua::MultiValue>(()).map_err(|error|Error::Lua{source,error})?;
+		// wait() is called from inside Lua and goes to a rust function that schedules the thread and then yields
+		// No need to schedule the thread here
+		Ok(())
 	}
 }