Im making a enemy for my game and when a player dies I want it to stop attacking. So I have a big function called dofight and i will call smaller fucntions in it that all have multiple wait lines. So my goal is to have a way to have the doFight function and all the ones it calls stop reading lines. What is the best way to do this?
local function doThrowRock()
print("Picking up rock")
task.wait(2)
print("Spinning rock")
task.wait(1)
print("Throwing rock")
task.wait(1)
end
local function doFight()
while true do
doThrowRock()
task.wait(0.5)
end
end
doFight()
You need to introduce a check to see if the fight loop should still keep going – also you need to run the loop on a different thread so the script keeps going.
This way would be the proper way to use a while loop, btw. You’re checking if the condition is true, and while it is true, do the thing. In your loop code, it’s just always true, that’s why it never ends.
Like this:
-- this will be the variable to check if the loop should keep going or not
local keepFighting = true
local function doFight()
while keepFighting == true do
doThrowRock()
task.wait(0.5)
end
end
-- use task.spawn so the fight loop doesn't block the rest of the script from running
task.spawn(function()
doFight()
end)
-- fighting now, let's wait a bit
task.wait(10) -- after 10 seconds...
keepFighting = false -- the fight should stop.
Wrap your doFight method in a coroutine, then use coroutine.close to kill the function when it is no longer needed.
Make sure the thread is still alive before attempting to close it, since otherwise it errors
local function doFight()
local co = coroutine.create(function()
...
end)
coroutine.resume(co)
return co
end
doFight()
...
if coroutine.status(co) ~= "dead" then
coroutine.close(co)
end
The thread gets marked as “yielding”, which allows another coroutine to run, when anything the coroutine run causes it to yield. So for your main question, it will also work with functions inside the coroutine
(and yes, task.wait will yield the running coroutine)