diff --git a/src/lib/globals/task.rs b/src/lib/globals/task.rs index 2db9241..59016e3 100644 --- a/src/lib/globals/task.rs +++ b/src/lib/globals/task.rs @@ -4,8 +4,8 @@ use std::{ }; use mlua::prelude::*; -use smol::prelude::*; use smol::{channel::Sender, LocalExecutor, Timer}; +use smol::{future::yield_now, prelude::*}; use crate::{utils::table_builder::TableBuilder, LuneMessage}; @@ -65,7 +65,6 @@ async fn run_registered_task( .await .map_err(LuaError::external)?; // Run the new task separately from the current one using the executor - // FIXME: This should run the task instantly and only stop at the first yield let sender = sender.clone(); let task = exec.spawn(async move { sender @@ -80,10 +79,13 @@ async fn run_registered_task( // to the main thread which will then handle them properly if run_in_background { task.detach(); - Ok(()) } else { - task.await.map_err(LuaError::external) + task.await.map_err(LuaError::external)?; } + // Yield once right away to let the above spawned task start working + // instantly, forcing it to run until completion or until it yields + yield_now().await; + Ok(()) } async fn task_cancel<'a>(lua: &'a Lua, thread: LuaThread<'a>) -> LuaResult<()> { diff --git a/src/tests/task/defer.luau b/src/tests/task/defer.luau index 22ba647..46884ea 100644 --- a/src/tests/task/defer.luau +++ b/src/tests/task/defer.luau @@ -10,18 +10,18 @@ task.defer(function() flag = true end) assert(not flag, "Defer should not run instantly or block") -task.wait(1 / 60) +task.wait(0.1) assert(flag, "Defer should run") -- Deferred functions should work with yielding local flag2: boolean = false task.defer(function() - task.wait(1 / 60) + task.wait(0.1) flag2 = true end) assert(not flag2, "Defer should work with yielding (1)") -task.wait(1 / 30) +task.wait(0.2) assert(flag2, "Defer should work with yielding (2)") -- Deferred functions should run after other spawned threads @@ -36,7 +36,6 @@ task.spawn(function() flag3 = true end end) -task.wait() assert(not flag2, "Defer should run after spawned threads") -- Varargs should get passed correctly