Hi all,
need help with this logical conundrum. (simplified for ease of solution).
For the purpose of the solution imagine both clients are running in the same script.
--Client 1 function TimeOut(secs) TimeOutEnd = false coroutine.resume(coroutine.create(function() for i = secs, 0, -1 do if TimeOutEnd then return end --irrelevant end end)) end --Client 2 TimeOut(20) -- this function will most likely fire before the original TimeOut function has completed it's cycle. button.MouseButton1Click:connect(function() TimeOutEnd = true TimeOut(20) end
What I would want is for the original TimeOut sequence to terminate it's cycle, and a new cycle to begin once again. Now the example above won't work because the means the instantaneous change from true back to false will have no effect with the one second interval.
I'd prefer not to yield the existing coroutine as I don't want useless threads lying around.
Thanks for your help guysh.
Nice question! I've run into this too. Here's my solution for this type of problem:
version = 0 function TimeOut(secs) version = version + 1 local curVersion = version coroutine.resume(coroutine.create(function() for i = secs, 0, -1 do --Do whatever wait(1) if version ~= curVersion then break end end end)) end
Every time TimeOut is called, the version variable is changed, causing any previously running TimeOut threads to stop executing (once they return from their 'wait' command).
If you're concerned about version
overflowing, you can modify the 3rd line to version = (version + 1) % 10000
or something, but it's probably not an issue because a number in lua can be precise until it hits a bit over 9x10^15 (exactly 2^53), and obviously that would take a lot of function calls.