Hi,
I use this coding pattern a lot in my projects, but it’s really clunky to set up.
I’m wondering if there’s a better way to set it up.
Current pattern I have set up.
local jobID = 0
local function foo()
--[[
Requirements of this function:
- only one instance of it should be running at any time
- the function can be called at any time, usually it'll be called during its yield of task.wait() periods
- if the function is already running and a new one is called, exit the old one
--]]
jobID = jobID + 1
local currentJobID = jobID
print("One", jobID)
task.wait(1)
if currentJobID ~= jobID then return end
print("Two", jobID)
task.wait(1)
if currentJobID ~= jobID then return end
print("Three", jobID)
end
for i = 1,10 do
task.defer(function()
-- here we use task.defer, but in the real world case, foo() is usually called by multiple connected events
foo()
end)
wait(0.25) -- we call the function faster than it's able to complete itself
end
Required Output:
One 1
One 2
One 3
One 4
One 5
One 6
One 7
One 8
One 9
One 10
Two 10
Three 10