I have 2 functions in a module for my round system. One of them checks if the round has ended (have all the players died, etc), and the other makes a timer for the round.
You may ask, can’t you just put the checking system in the timer? Well not really. It decreases the time every second, and I want the timer to instantly stop when a condition is met.
So here’s what I need help with:
Running 2 functions from a module at once
Being able to stop any one of them when a condition is met instantly
If you have a loop of code running continuously then you can use a while loop where the condition is a variable you toggle.
local Module = {}
function Module.Start(...)
module.Toggle = true
coroutine.wrap(function()
while module.Toggle do
--// action
end
end)()
end
function Module.Stop()
module.Toggle = false
end
return Module
local Module = require(...)
Module.Start()
Module.Stop()
A coroutine in lua can be thought of as a thread. It provides what looks like multi-threading in a single-threaded language. I just think of each coroutine I create as a separate thread that code can run on without affecting any other thread(s).
The world is not printed second because the wait(1) and print"hello' are inside their own thread and inside that thread there is a 1 second wait before hello would be printed.
coroutine.wrap returns a function–that is why I am calling the result from it. You could also assign a variable to the returned function and call that.
local thread = coroutine.wrap(func)
thread(...) -- ... are args that will be passed to func.
-- func will also be ran as if it was synchronous
-- this means that if func errors or has any sort of yielding, the code below
-- still runs
print"hello"