How would I return to the start of a loop?

How would I return a loop to its start?

Example, what if I wanted this code to go back to line 1 rather than continue normally?

local Amount = 1

while task.wait() do
  Amount += 1

  if Amount == 5 then
        print("Reached 5")
        Amount = 0
        --Return to start somehow
  end
end

You’re looking for a function:

local function doStuff()
    local Amount = 1

    while task.wait() do
        Amount += 1

        if Amount == 5 then
            print("Reached 5")
            Amount = 0
            --Return to start somehow
            doStuff()
        end
    end
end
doStuff()

Also if you’re looking to do something infinitely, you can do something like this:

while true do
    local amount = 1
    while true do
        amount += 1
        if amount == 5 then
            break
        end
        task.wait()
    end
end

Thanks a lot that makes sense, I don’t know how I didn’t think about that earlier :skull:

1 Like

Also return is an easier way.

Wdym? return would just stop the thread.

Return doesn’t do that. It returns a value and stops a thread i.e.

local function blah()
   return "Hi"
end

print(blah())

--Output: Hi
while true do
    amount = 1
    repeat task.wait()
    amount += 1
    until amount == 5
end

Just another way to do it. :smiley: (I think)

1 Like

My bad, a little rusty in the lua department, also having come from other languages.

here is a link about recursion, it basically talks about what Cody showed

thought this might be helpful

1 Like

thanks but i already know how recursion works, i was asking how to return to the start of a loop

1 Like

I know what the question was, I just sent the link incase you didn’t know much about it

my bad

1 Like