They both seem to achieve the same thing? So what's the difference between the two?
spawn(function() while wait(1) do print("spawned") end end)
coroutine.resume(coroutine.create(function() while wait(1) do print("coroutine") end end))
I find it easier to type spawn() over coroutine so I just use it instead.
If you just want two things to happen at once, use spawn
. If you want this, make sure you really want this -- usually, you don't need it.
When you just want to spawn a new "thread", you should use spawn
.
Coroutines are a really powerful feature of Lua. If your code doesn't make use of coroutine.yield
, though, there's no difference from just using spawn
.
The Programming in Lua book has a lot of examples on coroutines.
In particular, coroutines make nice iterators.
Let's say we want to print out all of the fibonacci numbers:
function fib(n) if n <= 1 then return n else return fib(n - 1) + fib(n - 2) end end for i = 1, 100 do print(fib(i)) end
While it might be nice to do it this, way, the way we have fib
written is really, really slow (try it out...!)
A faster fib
would look like this:
function fib(n) local a, b = 0, 1 for i = 1, n do a, b = b, a + b end return a end
But if we use this, we'll still be wasting a bunch of work, because we'll count all the way up each time.
Instead, we can make a coroutine that we repeatedly ask for numbers:
function fibGenerator() return coroutine.create(function() local a, b = 0, 1 while true do a, b = b, a + b coroutine.yield(a) end end) end local fibs = fibGenerator() for i = 1, 10 do local success, value = coroutine.resume(fibs) print( value ) end
EDIT: coroutine.resume
also returns a success
boolean. This will be false
if the coroutine is dead, e.g., won't be calling yield
ever again. In this case, the coroutine keeps working forever, so there's no point in paying attention to what success
is.
Essentially, coroutine.resume
is like "calling" the function, and coroutine.yield
is like "returning" from the function, but picking up from the same spot as last time.
this was a conversation on the forums about this, this might tell you which is better to you http://de.roblox.com/Forum/ShowPost.aspx?PostID=93520563
Locked by JesseSong
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?