Hey, the title basically explains the whole point of this topic.
I was wondering what the point of the spawn and delay functions are.
Hey, the title basically explains the whole point of this topic.
I was wondering what the point of the spawn and delay functions are.
They schedule a function to be run in an asynchronous manner of the parent Lua thread.
spawn - Runs a function at the next available Lua yield
delay - Runs a function after a minimum time has passed
They won’t block your existing code.
spawn(function()
while wait() do
print("a")
end
end)
while wait() do
print("b")
end
Both loops run asynchronously.
spawn
is more simple form of coroutines
. Coroutines seems to execute immediately compared to spawn
. This includes delay
which seems to have inherently the same extra time before execution.
spawn is the same thing as coroutines except spawns do one “wait()” before executing
While it doesn’t explain either of them itself, you might be interested in this lengthy technical discussion about the use of spawn and coroutines. Taught us all involved a good few things:
Other than that, spawn and delay are functions intended to essentially pseudothread, meaning code whose execution is independent from the current thread (Lua is single threaded so by this it means code in spawn or delay won’t terminate your threads). One waits a frame (not guaranteed to run), the other waits a bit before running (same deal).
Simple. Spawn()
Lets the code block not yield the script. For example:
You want to make Hi
print without waiting 1 second, but you also want to say Bye
after one second. Here are the two options you can take:
Print("Hi")
Wait(1)
Print("Bye") -- Output: Hi --> 1 second after -> Bye
or
spawn(function()
wait(1)
Print("Bye")
end)
Print("Hi") -- Output: Hi --> 1 second after -> Bye
Spawn functions are really useful in:
Serversided Cooldowns - Unhackable cooldowns
Waiting for a animation to stop without making the rest of the script wait for it to stop.
Personally, I use spawn()
functions alot. I never had any use of them till I understood what they could do.
Here’s why you woul want to use this.
Example: You would want to say Hi, Bye and Goodbye in different times.
You want to say Hi immediately, Bye after a second and Goodbye after 5 seconds.
Print("Hi")
spawn(function()
wait(1)
Print("Bye")
end)
wait(5)
Print("Goodbye") -- Since we used a spawn function the script will not wait for 6 seconds. Instead it will wait for 5 exact seconds.