I’m writing my own data saving and loading module, and I just had a quick question - How many times does one coroutine.create() function run?
Basically, for each player, I have a coroutine that will run, changing a value by one second each time. This currently works just fine, because I am creating and running the coroutine from within the main script. But, if I do something like:
myDataModule.ChangeValue = coroutine.create(function(player:Player)
--do stuff here
end)
will it create a new coroutine for each player that joins the game, or just overwrite what is currently there (the coroutine that is already running)?
From what I read here, it seems like it will simply create a coroutine and when it continues as normal via coroutine.resume, I’m not sure if I understood your question properly though. So if I misunderstood, please let me know.
I don’t think you quite understood it, but you were close . What I mean is within the loading function, if I resume a coroutine:
local function load(player:Player)
--do stuff
coroutine.resume(myDataModule.ChangeValue, player)
end
but the coroutine is already running from a previous player that joined, does it stop the other coroutine from running or does that coroutine run alongside the other coroutine?
In my opinion, this really does seem like a odd way of achieving this, but to answer your question, I’m pretty sure when a coroutine is already running and you try to resume it with a different player, the coroutine will pause its current work and start working for the new player. It won’t stop the previous work; both will run separately, each keeping track of its own progress for the respective players. I could be wrong though, so please do correct me @12345koip
– EDIT @fellow_meerkat’s explanation is WAY better and clears things up a bit more.
Alright, that’s all I wanted to know. I appreciate the help!
I used a coroutine because I have three operations like this running at once that refresh at different intervals (one for autosave, one for this, and one for another thing) so I thought this might be the best way to do it. If you have any other ideas, please do let me know
I’ll create a separate coroutine for each player within the loading function.
Quite close, but a single coroutine won’t run two separate threads. Resuming a coroutine with an ongoing yielding loop doesn’t do what it may seem at first sight.
local c = coroutine.create(function(arg)
while true do
print(arg); task.wait(1)
end
end)
coroutine.resume(c, 1)
coroutine.resume(c, 2)
Appreciate the info. I think I’ll stick to making a seperate coroutine for each player (it will end if the player leaves), because it’d be a bit of a hassle to check every saving player, and add a new one, whenever a player leaves/join. Appreciate the help from both of you