Handling multiple timers in a single script/module

Hello!

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.

2 Likes

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

It would be better if you do it in the main script as that looks like a waste of lines to me. Or you can bring the whole game managment to the module.

I’m not so good with modules and I don’t think you can pass a function as an argument.

1 Like

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?

1 Like

Yes, correct.

Just an FYI

There’s also coroutine.create and coroutine.resume which do the same thing as coroutine.wrap

local Coroutine = coroutine.create(Lobby1)
coroutine.resume(Coroutine)

Edit: There’s also spawn implemented by Roblox

1 Like

Got it, thanks! I’ll keep your original response as the answer though, as it’s more informational.

1 Like