I am currently working on a game that has four lobbies, each should have a 30 second countdown as soon as the first player joins, and then if they leave, the timer stops. Since a loop is already running, doesn’t this mean no other functions can be interacted with? I was thinking something like this:
function Lobby1()
for i=1,30 do
wait(1)
end
end
function Lobby2()
for i=1,30 do
wait(1)
end
end
…etc all the way to Lobby4. The issue is, won’t that mean multiple functions can’t run in a single scripts at one time? Pretty much a yes or no question, however I don’t want to put in all of the work to have it end up not working.
Yes you are correct. It will be ran alone until it end then goes to the next function.
Unless you use a coroutine like this.
function Lobby1()
for i=1,30 do
wait(1)
end
end
function Lobby2()
for i=1,30 do
wait(1)
end
end
coroutine.wrap(Lobby1)
Coroutines basically make a new thread allowing a function to run freely without disturbing the code beneath it.
From what I have heard, coroutines are automatically garbage collected after they end running (in luau) so no need to worry about memory leaks on that extent.
Just out of curiosity, do you recommend using this in a module? If so, how would I do that?
Would something like this work?
module = {}
function module:StartTimer(lobby)
coroutine.wrap(lobby) -- just connect to whichever function, hadn't included it in this example for simplicity.
end
return module
No, you can’t pass it like that IIRC, I will probably just do it in a single script as you said. So I just wrap the function in a coroutine and that should work?