Task Library - Now Available!

The defer method schedules code for resumption at the end of the current (or next if we aren’t currently in one) resumption point. You can think of it as adding something to the back of the queue of threads we are going to resume.

So it’s useful in cases such as the example given by @tnavarts and the one you’ve shared here but it can also be useful for other purposes too.

  • Scheduling custom events to run later so they don’t affect the current code (we do this with deferred events)
  • Coalescing state changes so code only runs once

An example of the latter might be a case where you only care about the final value of something and not any intermediary values:

local currentRequestTime = 0

local function performDataSave(requestTime)
    if requestTime < currentRequestTime then
        return -- a newer data-save was requested
    end
    -- save data
end

local function queueDataSave()
    currentRequestTime = os.clock()
    task.defer(performDataSave, currentRequestTime)
end

instance:GetAttributeChangedSignal("Points"):Connect(function ()
    queueDataSave()
end)

Of course there are other ways to implement this but this is one such way to do it.

4 Likes

Hey, sorry if I’m missing something in terms of engine implementation detail, but what difference is there in simply calling the Object::Destroy method directly and using task.defer? What engine detail is changed? Going off the comment of it being destroyed instantly, does calling the method directly have a form of delay before the object is destroyed?
Many thanks beforehand.

1 Like

Awesome!. Now I can’t wait for Roblox to add more pcall(), and a few other things in Lua Globals and Roblox Globals.
Hope so!

Adding onto this: does task.defer add some performance benefit over task.spawn / spawn / coroutines? Since it’s stated it doesn’t care for exact timing and all.

1 Like

Changing the parent of an instance during a parent change operation will result in the following warning being shown and the parent remaining the same.

Something unexpectedly tried to set the parent of <Instance> to NULL while trying to set the parent of <Instance>. Current parent is <Parent>.

When signaling behavior is set to immediate (the default), ancestry changed events fire during the parent change operation so running the code in @tnavarts’s example, where ‘Destroy’ is called directly, will produce the warning above.

By deferring the call to ‘Destroy’, the parent change happens after the parent change operation but still within the same resumption cycle (so almost immediately).

The code doesn’t run immediately but will still be processed before the engine can move onto its next step. It’s not really any different other than it doesn’t block the code which is currently running.

4 Likes

whats the advantage over coroutine.wrap?

1 Like

I think you should rather replace the behavior of the old wait() with the new task.wait()

Isn’t this a bug in Roblox which should be fixed?

It’s not a “bug” in that coroutine.wrap / coroutine.resume propagate errors in the same way that they do in vanilla Lua, they just don’t have the extra behavior that Roblox adds for convenient debugging in Studio. It makes sense to have a separate library like this if you want the Roblox behaviors so that vanilla Lua code can be brought into the engine from other sources and work as expected.

3 Likes

I see no need for this at all
task.wait() is fine as it is, besides if wait() is deprecated then it WON’T be updated anymore, it is still going to be useable so older games don’t break

I don’t think it’s all evil in all honestly. I use spawn() mainly for its task scheduler functionality which helps performance a lot in looped events such as character leg movement replication, bullet replication and stuff which doesn’t need to be ran instantly

@WallsAreForClimbing and @tnavarts, looking at the spec provide for task.wait() and docs for wait() you can see they do not return the same number of parameters. wait() returns the duration and the total game time, whereas task.wait() is only returning the duration. Devs should be aware of this difference when updating their code.

Is there any reason to not make task.wait return both parameters?

Below is the last 4 lines of the current Character.Animate script for reference. You will get unexpected behaviour assuming they are equivalent and just replace wait() with task.wait().

while Character.Parent ~= nil do
    local _, currentGameTime = wait(0.1)
    stepAnimate(currentGameTime)
end

changing to task.wait(0.1) will not give you the expected results:

while Character.Parent ~= nil do
    local _, currentGameTime = task.wait(0.1)
    stepAnimate(currentGameTime)
end
3 Likes

Does this mean that task.wait() has a minimum time of 1/60 instead of wait()'s minimum time of 1/30?

1 Like

Much less than 1/60 in fact!

game:GetService("RunService").RenderStepped:Wait() 
print(task.wait())  --> 0.00097130000000334

If you task.wait() during the Heartbeat part of the frame, then it will wait until the next Heartbeat (roughly 1/60), but if you task.wait() in an earlier part of the frame (such as on RenderStepped), it won’t even wait a full frame, it will unsuspend on Heartbeat of the same frame.

For reference, a frame works like this:

image

15 Likes

Are you sure about this? If you create a LocalScript, do task.spawn(function() while wait(1) print(1) end), and then delete it, it will stop printing.

2 Likes

Very much yes! Is this a solution to deferred events? Will this allow Parallel Luau to exist without breaking all event-handling code across all existing games?

Are you able to disconnect task.delay? I want to disconnect task.delay if a certain condition is met so it doesn’t run and I’m having trouble doing that.

Can’t you just add an if statement inside the function passed to task.delay and check if a certain condition met like that?

This is what I’m trying to do basically. Say you press the F key, it will turn the part red, then after 0.5 seconds, it will turn the part green. However, if you press the F key while the part is red, then I want it to disconnect the current task delay, and add another 0.5 seconds of wait time before the part turns green. I can’t think of another solution, I’m probably missing something obvious, any help would be appreciated.

    local conn
    function TurnPartRed()
        if conn ~= nil then
            conn:Disconnect()
            conn = nil
        end

        Part.Color = Color3.fromRGB(255,0,0)
        conn = task.delay(0.5, function()
            Part.Color = Color3.fromRGB(0,255,0)
        end)
    end

You can add a variable that stores the last time F key was pressed then check if current time subtracted by the latest F key input time is bigger equal than 0.5:

    local conn
    local LastFKeyPressTime = 0
    function TurnPartRed()
        if conn ~= nil then
            conn:Disconnect()
            conn = nil
        end
        
        LastFKeyPressTime = os.clock()
        Part.Color = Color3.fromRGB(255,0,0)
        conn = task.delay(0.5, function()
            if os.clock() - LastFKeyPressTime >= 0.5 then
                Part.Color = Color3.fromRGB(0,255,0)
            end
        end)
    end
2 Likes