What do spawn functions do?

I see people use spawn functions sometimes in scripts, but I really don’t see what the actual use is.
Does anyone know the actual use for them?

6 Likes

spawn is obsolete and task.spawn must be used, this makes the required function run immediately.

4 Likes

Lua uses cooperative multithreading, which means that multiple threads of execution (otherwise known as coroutines) can run “at the same time”.

Spawning (via task.spawn) is simply a way to tell Roblox to run a function in the background while you continue to do other things.

19 Likes

Yeah still, what is the use though?

Why spawn is still there? they cannot remove it as many old scripts would break and, as a function, an example would be a while true do loop, this stops the script but to not place it at the bottom, or place 2 together, task.spawn would be used.

2 Likes

See my post above. Spawning a new coroutine (via task.spawn) is useful when you need to branch off from the current point without delaying the rest of the script.

For example:

-- doing something

task.spawn(function()
    -- do something
    task.wait(5)
    -- clean up
end)

-- continue doing something else even while that function is waiting

Spawning itself is not obsolete, but @SOTR654 is saying that the top-level spawn function is deprecated in favor of task.spawn, which does it in a much better way.

3 Likes

No, wasn’t asking about that though.

Sorry, this is a clearer example

print("1")
while task.wait() do
    print("test")
end
print("2")

because of the loop, 2 would never be printed, which is not the case with task.spawn

print("1")
task.spawn(function()
    while task.wait() do
        print("test")
    end
end)
print("2")

the loop will continue to run and the rest of the script too.

17 Likes