Hey devs! I have a question . I need to stop this loop when the function “CloseAll” was be called again.
Here I use a bool variable to know when the function was be called again.
local market_manager = {CancelPage = false}
function market_manager:CloseAll()
coroutine.resume(coroutine.create(function()
market_manager.CancelPage = true
wait()
market_manager.CancelPage = false
for i = 1, #market_folder do
if market_manager.CancelPage then
break
end
market_folder[i]:Closing()
end
end))
end
I want to know if is a good idea to do like that? Anyone have any suggestion to do?
And just for information, what’s the best of “spawn” and “coroutine.resume(coroutine.create(” I never know which used.
Make a variable x = 0 outside the function. Inside the function, increment the value: x = x + 1. Just after incrementing, make a local variable y = x. Inside the loop, check if the two variables are equal. If they are not, then break out of the loop: if x ~= y then break end.
You can toggle market_manager.CancelPage at the beginning of the function call. You’ll want it to probably default to true and then you can call the function code if not market_manager.CancelPage. Otherwise you can do nothing which means the value will be true and your old code will finish executing.
If you want it to default to false you need to set it to false again before running the function code and run it if market_manager.CancelPage.
Example:
local toggle = true
local function func()
toggle = not toggle -- Toggle the toggle
if not toggle then -- Toggle is true
while true do -- Example loop, below if statement would make more sense it condition but this better explains it with the OP's situation
wait()
if toggle then -- Toggle is true! Break the loop since the function was called
break
end
end
end
end
-- Call one, toggle switches to false
-- Loop starts
-- Function finishes
-- Call two, toggle switches to true
-- Function finishes
-- Loop stops
and on every call initialize it to the coroutine of the run, and set up a break statement for when the currentThread is initialized to a different thread. You can think of coroutine.running() in the sense of an id to the thread
local currentThread=nil
function runNew()
currentThread=coroutine.running() -- declares this thread as current thread
for i=1,n do
if currentThread~=coroutine.running() then -- Compares this thread with current thread
break
end
-- body of loop
end
end
coroutine.wrap(runNew)