Background information and why this matters
As a Roblox developer, it is currently impossible to run code after the current thread yields
Whenever you resume a thread, it is resumed immediately [1] (it even takes priority over the thread that calls the resume)
This is very useful in most cases, but often times its not what is desired
So right now if we want to run code after the current thread yields we have to resume a thread and, within this new thread, yield with a (nasty!) wait() for a little to delay the code’s execution until after the parent thread yields [2]
Not only is this counter-intuitive and a bad habit, but it’s also just terrible that we have to use this hacky yield (which may lead to very difficult to debug race conditions)!
If Roblox is able to address this, it would improve my development experience because I would not have to precariously hack my lua code
I also came across this issue a couple months ago when I was trying to emulate the queue in Roblox Remote Events with :Wait() (I don’t know if they actually support Wait releasing one element of the queue, if they do, they must use defer internally or have a hacky wait?)
1
local thread=coroutine.create(function()
print'inside new thread'
end)
print'start'
coroutine.resume(thread)
print'finish'
2
local thread=coroutine.create(function()
game:GetService'RunService'.Heartbeat:Wait()
print'inside new thread'
end)
print'start'
coroutine.resume(thread)
print'finish'
Proposed solutions
So I think golang has defer which basically lets you run code after a function returns
It would be nice if something similar existed in Roblox
My #1 preference would be if we had wait(0)
act as delaying the thread’s execution until the thread scheduler would normally sleep(that might not be the right term, but basically until the next thread to resume’s resume time is greater than tick())
If it is risky to use wait(0)
in this manner because of older games, then a new function like coroutine.resume_last(thread) or superfastwait()-bad name-that can accomplish the same thing would be really nice
Defer would work well too, but at this point it seems weaker than the other proposed solution(s)