Remove lua arg from runtime struct methods

This commit is contained in:
Filip Tibell 2024-01-20 11:18:00 +01:00
parent d1cc17b2d3
commit c00c07cf24
No known key found for this signature in database
7 changed files with 39 additions and 40 deletions

View file

@ -23,8 +23,8 @@ pub fn main() -> LuaResult<()> {
// Load the main script into a runtime and run it until completion // Load the main script into a runtime and run it until completion
let rt = Runtime::new(&lua)?; let rt = Runtime::new(&lua)?;
let main = lua.load(MAIN_SCRIPT); let main = lua.load(MAIN_SCRIPT);
rt.push_thread(&lua, main, ()); rt.push_thread(main, ());
rt.run_blocking(&lua); rt.run_blocking();
Ok(()) Ok(())
} }

View file

@ -29,8 +29,8 @@ pub fn main() -> LuaResult<()> {
// Load the main script into a runtime and run it until completion // Load the main script into a runtime and run it until completion
let rt = Runtime::new(&lua)?; let rt = Runtime::new(&lua)?;
let main = lua.load(MAIN_SCRIPT); let main = lua.load(MAIN_SCRIPT);
rt.push_thread(&lua, main, ()); rt.push_thread(main, ());
rt.run_blocking(&lua); rt.run_blocking();
Ok(()) Ok(())
} }

View file

@ -11,21 +11,18 @@ pub fn main() -> LuaResult<()> {
// Create a new runtime with custom callbacks // Create a new runtime with custom callbacks
let rt = Runtime::new(&lua)?; let rt = Runtime::new(&lua)?;
rt.set_callbacks( rt.set_callbacks(Callbacks::default().on_error(|_, _, e| {
&lua, println!(
Callbacks::default().on_error(|_, _, e| { "Captured error from Lua!\n{}\n{e}\n{}",
println!( "-".repeat(15),
"Captured error from Lua!\n{}\n{e}\n{}", "-".repeat(15)
"-".repeat(15), );
"-".repeat(15) }));
);
}),
);
// Load and run the main script until completion // Load and run the main script until completion
let main = lua.load(MAIN_SCRIPT); let main = lua.load(MAIN_SCRIPT);
rt.push_thread(&lua, main, ()); rt.push_thread(main, ());
rt.run_blocking(&lua); rt.run_blocking();
Ok(()) Ok(())
} }

View file

@ -26,8 +26,8 @@ pub fn main() -> LuaResult<()> {
// Load the main script into a runtime and run it until completion // Load the main script into a runtime and run it until completion
let rt = Runtime::new(&lua)?; let rt = Runtime::new(&lua)?;
let main = lua.load(MAIN_SCRIPT); let main = lua.load(MAIN_SCRIPT);
rt.push_thread(&lua, main, ()); rt.push_thread(main, ());
rt.run_blocking(&lua); rt.run_blocking();
Ok(()) Ok(())
} }

View file

@ -45,7 +45,7 @@ pub fn main() -> LuaResult<()> {
fn run<'lua>(lua: &'lua Lua, main: impl IntoLuaThread<'lua>) -> LuaResult<LuaValue> { fn run<'lua>(lua: &'lua Lua, main: impl IntoLuaThread<'lua>) -> LuaResult<LuaValue> {
// Set up runtime (thread queue / async executors) // Set up runtime (thread queue / async executors)
let rt = Runtime::new(lua)?; let rt = Runtime::new(lua)?;
let thread = rt.push_thread(lua, main, ()); let thread = rt.push_thread(main, ());
lua.set_named_registry_value("mainThread", thread)?; lua.set_named_registry_value("mainThread", thread)?;
// Create callbacks to capture resulting value/error of main thread, // Create callbacks to capture resulting value/error of main thread,
@ -54,7 +54,6 @@ fn run<'lua>(lua: &'lua Lua, main: impl IntoLuaThread<'lua>) -> LuaResult<LuaVal
let captured_error = Rc::new(Mutex::new(None)); let captured_error = Rc::new(Mutex::new(None));
let captured_error_inner = Rc::clone(&captured_error); let captured_error_inner = Rc::clone(&captured_error);
rt.set_callbacks( rt.set_callbacks(
lua,
Callbacks::new() Callbacks::new()
.on_value(|lua, thread, val| { .on_value(|lua, thread, val| {
let main: LuaThread = lua.named_registry_value("mainThread").unwrap(); let main: LuaThread = lua.named_registry_value("mainThread").unwrap();
@ -71,7 +70,7 @@ fn run<'lua>(lua: &'lua Lua, main: impl IntoLuaThread<'lua>) -> LuaResult<LuaVal
); );
// Run until end // Run until end
rt.run_blocking(lua); rt.run_blocking();
// Extract value and error from their containers // Extract value and error from their containers
let err_opt = { captured_error.lock_blocking().take() }; let err_opt = { captured_error.lock_blocking().take() };

View file

@ -24,8 +24,8 @@ pub fn main() -> LuaResult<()> {
// Load the main script into a runtime and run it until completion // Load the main script into a runtime and run it until completion
let rt = Runtime::new(&lua)?; let rt = Runtime::new(&lua)?;
let main = lua.load(MAIN_SCRIPT); let main = lua.load(MAIN_SCRIPT);
rt.push_thread(&lua, main, ()); rt.push_thread(main, ());
rt.run_blocking(&lua); rt.run_blocking();
Ok(()) Ok(())
} }

View file

@ -16,7 +16,8 @@ use super::{
const GLOBAL_NAME_SPAWN: &str = "__runtime__spawn"; const GLOBAL_NAME_SPAWN: &str = "__runtime__spawn";
const GLOBAL_NAME_DEFER: &str = "__runtime__defer"; const GLOBAL_NAME_DEFER: &str = "__runtime__defer";
pub struct Runtime { pub struct Runtime<'lua> {
lua: &'lua Lua,
queue_status: Rc<Cell<bool>>, queue_status: Rc<Cell<bool>>,
// TODO: Use something better than Rc<Mutex<Vec<...>>> // TODO: Use something better than Rc<Mutex<Vec<...>>>
queue_spawn: Rc<Mutex<Vec<ThreadWithArgs>>>, queue_spawn: Rc<Mutex<Vec<ThreadWithArgs>>>,
@ -25,14 +26,14 @@ pub struct Runtime {
rx: Receiver<()>, rx: Receiver<()>,
} }
impl Runtime { impl<'lua> Runtime<'lua> {
/** /**
Creates a new runtime for the given Lua state. Creates a new runtime for the given Lua state.
This will inject some functions to interact with the scheduler / executor, This will inject some functions to interact with the scheduler / executor,
as well as the default [`Callbacks`] for thread values and errors. as well as the default [`Callbacks`] for thread values and errors.
*/ */
pub fn new(lua: &Lua) -> LuaResult<Runtime> { pub fn new(lua: &'lua Lua) -> LuaResult<Runtime<'lua>> {
let queue_status = Rc::new(Cell::new(false)); let queue_status = Rc::new(Cell::new(false));
let queue_spawn = Rc::new(Mutex::new(Vec::new())); let queue_spawn = Rc::new(Mutex::new(Vec::new()));
let queue_defer = Rc::new(Mutex::new(Vec::new())); let queue_defer = Rc::new(Mutex::new(Vec::new()));
@ -111,6 +112,7 @@ impl Runtime {
Callbacks::default().inject(lua); Callbacks::default().inject(lua);
Ok(Runtime { Ok(Runtime {
lua,
queue_status, queue_status,
queue_spawn, queue_spawn,
queue_defer, queue_defer,
@ -124,8 +126,8 @@ impl Runtime {
This will overwrite any previously set callbacks, including default ones. This will overwrite any previously set callbacks, including default ones.
*/ */
pub fn set_callbacks(&self, lua: &Lua, callbacks: Callbacks) { pub fn set_callbacks(&self, callbacks: Callbacks) {
callbacks.inject(lua); callbacks.inject(self.lua);
} }
/** /**
@ -133,18 +135,19 @@ impl Runtime {
Threads are guaranteed to be resumed in the order that they were pushed to the queue. Threads are guaranteed to be resumed in the order that they were pushed to the queue.
*/ */
pub fn push_thread<'lua>( pub fn push_thread(
&self, &self,
lua: &'lua Lua,
thread: impl IntoLuaThread<'lua>, thread: impl IntoLuaThread<'lua>,
args: impl IntoLuaMulti<'lua>, args: impl IntoLuaMulti<'lua>,
) -> LuaThread<'lua> { ) -> LuaThread<'lua> {
let thread = thread let thread = thread
.into_lua_thread(lua) .into_lua_thread(self.lua)
.expect("failed to create thread"); .expect("failed to create thread");
let args = args.into_lua_multi(lua).expect("failed to create args"); let args = args
.into_lua_multi(self.lua)
.expect("failed to create args");
let stored = ThreadWithArgs::new(lua, thread.clone(), args); let stored = ThreadWithArgs::new(self.lua, thread.clone(), args);
self.queue_spawn.lock_blocking().push(stored); self.queue_spawn.lock_blocking().push(stored);
self.queue_status.replace(true); self.queue_status.replace(true);
@ -159,7 +162,7 @@ impl Runtime {
Note that the given Lua state must be the same one that was Note that the given Lua state must be the same one that was
used to create this runtime, otherwise this method may panic. used to create this runtime, otherwise this method may panic.
*/ */
pub async fn run_async(&self, lua: &Lua) { pub async fn run_async(&self) {
// Create new executors to use // Create new executors to use
let lua_exec = LocalExecutor::new(); let lua_exec = LocalExecutor::new();
let main_exec = Arc::new(Executor::new()); let main_exec = Arc::new(Executor::new());
@ -167,7 +170,7 @@ impl Runtime {
// TODO: Create multiple executors for work stealing // TODO: Create multiple executors for work stealing
// Store the main executor in lua for LuaExecutorExt trait // Store the main executor in lua for LuaExecutorExt trait
lua.set_app_data(Arc::downgrade(&main_exec)); self.lua.set_app_data(Arc::downgrade(&main_exec));
// Tick local lua executor while also driving main // Tick local lua executor while also driving main
// executor forward, until all lua threads finish // executor forward, until all lua threads finish
@ -198,7 +201,7 @@ impl Runtime {
for queued_thread in queued_threads { for queued_thread in queued_threads {
// NOTE: Thread may have been cancelled from lua // NOTE: Thread may have been cancelled from lua
// before we got here, so we need to check it again // before we got here, so we need to check it again
let (thread, args) = queued_thread.into_inner(lua); let (thread, args) = queued_thread.into_inner(self.lua);
if thread.status() == LuaThreadStatus::Resumable { if thread.status() == LuaThreadStatus::Resumable {
let mut stream = thread.clone().into_async::<_, LuaValue>(args); let mut stream = thread.clone().into_async::<_, LuaValue>(args);
lua_exec lua_exec
@ -207,8 +210,8 @@ impl Runtime {
// drop it right away to clear stack space since detached tasks dont drop // drop it right away to clear stack space since detached tasks dont drop
// until the executor drops https://github.com/smol-rs/smol/issues/294 // until the executor drops https://github.com/smol-rs/smol/issues/294
match stream.next().await.unwrap() { match stream.next().await.unwrap() {
Ok(v) => Callbacks::forward_value(lua, thread, v), Ok(v) => Callbacks::forward_value(self.lua, thread, v),
Err(e) => Callbacks::forward_error(lua, thread, e), Err(e) => Callbacks::forward_error(self.lua, thread, e),
}; };
}) })
.detach(); .detach();
@ -231,7 +234,7 @@ impl Runtime {
See [`ThreadRuntime::run_async`] for more info. See [`ThreadRuntime::run_async`] for more info.
*/ */
pub fn run_blocking(&self, lua: &Lua) { pub fn run_blocking(&self) {
block_on(self.run_async(lua)) block_on(self.run_async())
} }
} }