The wording for the topic will mention how you shouldn’t use
:Waitthat is because I was using that as the title name for a while.
This subject is way more complex than just stopping to use
:Wait, you SHOULD use
:Waitfor most cases.
This is in case you’re specifically using BindableEvents or some Signal API to wait for somrthing to happen in another coroutine.
- You can get a coroutine instance from any script, anywhere, anytime using
coroutine.running! Every script runs in a separate coroutine.
- Roblox threads can behave differently, they are still get-able through
coroutine.running, but they behave a little difference depending on what you do on them, in this case using
coroutine.yield / resumecan have a slightly different effect which you can read about here.
An example might be having a timer system using a RunService event and you wanna resume the code once the timer finishes.
local RunService = game:GetService('RunService') local timeLeft = 10 local Event = Instance.new('BindableEvent') local connection; connection = RunService.Heartbeat:Connect(function(delta) timeLeft -= delta; if timeLeft <= 0 then connection:Disconnect(); Event:Fire(); end end) Event.Event:Wait() Event:Destroy()
And the problem here, is memory usage. Lua memory management sometimes is weird in my experience, and overall if you can use less memory in a still reasonable matter, then why not?
If you’re using a Signal API or a BindableEvent, you have more garbage data that you might think.
In a custom Signal API you’re gonna be holding references to a lot of tables sometimes, and for BindableEvents, you have properties like Name, a bunch of sub events like
And anyhow, custom Signal APIs, ones that don’t use BindableEvents, are gonna be using the ‘tip’ internally which I show here, except that these Signal APIs will use way more memory than just using this purely.
It’s super simple, here’s an example of the previous script except with these functions.
local RunService = game:GetService('RunService') local timeLeft = 10 local thread = coroutine.running() --// Gets the 'coroutine' instance were in. local connection; connection = RunService.Heartbeat:Connect(function(delta) --\\ Connections are ran in another coroutine instance. timeLeft -= delta; if timeLeft <= 0 then connection:Disconnect(); coroutine.resume(thread); end end) coroutine.yield() --\\ 'Pauses' the current 'coroutine' instance.