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
Thanks!
1 Like
you cant run them ‘at once’, but you can use a coroutine to run them very close to ‘at once’ incase one of them is yielding.
coroutine.wrap(module.functionA)(...)
coroutine.wrap(module.functionB)(...)
2 Likes
Alright, but do you know how to instantly stop one of them when a condition is met?
1 Like
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()
You should put this in a coroutine so you can still call the stop function.
Meant to write one–thanks for catching that.
My problem is that in the while loop I’d have a wait(1) and wouldn’t that cause some delay? If this can’t work out it’s fine.
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).
coroutine.wrap(function()
wait(1)
print"hello"
end)()
print"world"
this would output:
world
hello
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"
https://www.lua.org/pil/9.html
1 Like