Coroutine loop restart?

Basically its a Patrol function which contains a loop which only runs if the value loop is true. However, I want to switch it to coroutines as the Loop = false is used in the same code thus no point in having a loop value if it can be stopped by another function, plus that spawn() is said to cause a delay before starting. I don’t seem to get how to use it in this specific case as I dont usually use coroutines.

The loop cycle should start from the begining. However it can be cut no problem without finishing the cycle. But I found that the coroutine.yield continues the loop, instead of restarting it.

local Loop = true

function Patrol()
    --variables, etc
    spawn(function() --want to replace this with a coroutine that can be stopped/reset somewhere else in the script
        repeat
            wait(0.5) --cooldown between loops
             --patrol code
        until not Loop
    end)
end

End = function()
    Loop = false
end

Hello, you can use coroutine for numerous of times if you assign coroutine as a variable.

An example will be as below:


local newCoroutine = coroutine.wrap(function()
    repeat
        wait(0.5)
    until not Loop
end)
newCoroutine()

Yes but can I yield it from another function in the script, and on the newCoroutine.resume have it start over?

No, I guess you can’t yield it from another function. But it will start over if you call it again. And for per your usage, you should cover the coroutine with function once again.

May I ask you why are you willing to yield coroutine?


local function newCoro()
    local newCoroutine = coroutine.wrap(function()
        repeat
            wait(0.5)
        until not Loop
    end)
    newCoroutine()
end

It is supposed to be a patrol function, which should stop if the NPC found a player. However when called, supposed to run a new cycle not start in a previous cycle. I want to remove the repeat ... until not Loop

Currently reached this:

    PatrolLoop = coroutine.create(function()
        --code
        coroutine.yield()
    end)

Where it will yeild after just one cycle and will recall it if no players are in range yet.
That way each time its called it will do a full cycle.

local Loop = true

coroutine.wrap(Patrol()
        --variables, etc
        while true do
            wait(0.5)
             --patrol code
            if Loop == false then
               coroutine.yield()
            end
        end
end)

this will yield the coroutine when it reaches its target, and yield(), or pause the coroutine. Then, you can call it again by doing Patrol(), and setting Loop = true.

2 Likes