Hi, is there a way I can cancel a function, even while its running? Something like this:
local function loop()
while true do
wait(10)
end
end
can I cancel it before the while loop finishes?
Hi, is there a way I can cancel a function, even while its running? Something like this:
local function loop()
while true do
wait(10)
end
end
can I cancel it before the while loop finishes?
Are you talking about the break
function? You can use this function to break out of loops. You can see more info about it here: Programming in Lua : 4.4
Yes, about that, I’ve tried to use break, but for that to work I would have to wait for the while loop to finish, so I need a way to cancel the function ideally, even during the loop.
In the beginning of the loop you can have an if statement that can break the loop if true.
while true do
if 1 + 1 = 2 then
break
end
--your code
end
I understand what you are saying, but I just tried it and it didn’t work. I’m pretty sure it’s because the loop finishes, then when it returns back to the if statement, it then breaks. But is there a way I can break the loop, or cancel a function in the middle of the loop?
You can use coroutines to run functions in parallel to other code and “stop” the function mid way through, no matter what it’s doing. However, you’ll have to be sure what you’re doing really requires the use of a coroutine to work. Often you’ll find that when you think about it from a different approach, you won’t need as much as you realise.
So I can use coroutine.create(), and put my other function in there, and then use coroutine.yield() and it will pause the function?
Would the continue
function be viable here?
Yeah that worked really well, if I understand correctly, it just skips the rest of the code in the loop, and the loop resets from there if the value == true holds up?
You can use return to return nil, although this might not be the best option if such function returns values normally
I think I’m going to just rewrite the code with a for i = loop because from what i’ve seen over the past hour is people explaining different ways that don’t work for this scenario, thanks for helping out everyone.
And the continue function I realized kept the function still running, and it only broke the loop, so it kind of messed things up