Is there a way to create loops in the middle of a script but still make it continue while the loop is running?

I’m trying to make a Script where I start a loop inside the Script and continue while the loop is still running. I already tried coroutines and task.spawn, but these don’t seem to work, is there any other way?

Example:

-- random code before this

local Players = game:GetService("Players")
local plrAmount = #Players:GetPlayers()
local var = true

local function x()
    while var do
        task.wait()
        var = false
        if plrAmount < 12 then
           -- ...
        end
        var = true
    end
end

-- task.spawn(x())
-- or
-- local crx = coroutine.create(x())
-- coroutine.resume(crx)
-- don't work

-- code after this should run while the loop is running
2 Likes

Well task.spawn should work for this:

local function x()
    print("Before")
    task.spawn(function()
        while var do
            task.wait()
            var = false
            if plrAmount < 12 then
               -- ...
            end
            var = true
        end
    end)
    print("Loop still running")
end

Use coroutine, spawn, or task.spawn. Coroutine is preferred for handling threads (the object that is returned from coroutine.create).

This doesn’t work because you only need to point it to a function in memory like this

task.spawn(x)
1 Like

Try using Croutine for it. Look into it I’m not going to go into a full in-depth tutorial today. I hope this answers your problem.

personally i use coroutine.wrap for this, but there are other ways. idk what coroutine.create or coroutine.resume do because i never had to use them but this is what i would do

coroutine.wrap(function()
    --do stuff here
end)() -- make sure you put that there otherwise it wont run
5 Likes

Thanks so much, this worked for me!