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?
spawn
is obsolete and task.spawn
must be used, this makes the required function run immediately.
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.
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.
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.
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.