I've asked a question similar to this before, however i feel this is a lot different. I know you wouldn't create a coroutine specifically for running a few lines of code at once, since their purpose is much greater than just running code at the same time.
But is coroutine.wrap an exception? I've seen in tons of scripts people using something like:
coroutine.wrap(function() repeat wait(1) Something = Something + 1 until nil end)() -- when it could be: spawn(function() repeat wait(1) Something = Something + 1 until nil end)
But, wouldn't spawn be better? Or at least more practical? If anyone knows this a bit more than I do, I'd appreciate your insight.
Let's see here...
coroutine.wrap
returns a function that resumes the coroutine when it is called...
spam = coroutine.wrap(function(argument) while true do for i = 1, 1000 do print(argument) wait() end coroutine.yield() end end) spam 'hey' for i = 1, 1000 do print 'hi' wait(.04) end
...And then you have spawn
, which can give you the elapsed time and how long the game has been running...
spawn(function(elapsed, current) for i = 500, 600 do print(i) pcall(function() game.Players:GetNameFromUserIdAsync(i) end) end print(elapsed, current) end)
...And that's all I got. If you just want a new thread and don't need either of these features, use either one.
"you wouldn't create a coroutine specifically for running a few lines of code at once, since their purpose is much greater than just running code at the same time"
I'm not sure what you mean by this, since that is their purpose - to run different lines of code "simultaneously" (technically they take turns running instead of actually running at the same time - one only stops running when it yields, and the game (including workspace.DistributedGameTime) only advances once all coroutines have yielded).
The difference between Spawn and coroutine.wrap is here: "Spawned functions and coroutines aren't used in the same way. Spawn is used to delay the execution of a functions until the thread yields while coroutines are used to run code immediately on a separate thread."
In the example of your code, there's practically no difference - it's just that the coroutine calls "wait" immediately, whereas "spawn" will call "wait" sometime after the current thread yields (but before workspace.DistributedGameTime has been advanced). In this case, the code will proceed the same way in either case.