How To Make A Loop Return Back To The Beginning

What I want achieve is a loop that checks a conditional statement, and if that statement is true it’ll wait 10 seconds and check if that statement has changed, if it has changed it should return to the top, if it hasn’t then it should run the last conditional statement.

j = 0
while true do
   wait(5)
   if j == 0 then
   	wait(10)
   	
   if j == 1 then
   -- If j has changed then I want the loop to go back to the Beginning
   if j == 0  then
   -- If j has not changed then it will run whatever code I want below
   	
   		end			
   end
end
3 Likes
j = 0
while true do
    wait(5)
    if j == 0 then
        wait(10)
        if j == 0 then
            -- code
        end
    end
end

Either one of statements are false; thus skipping and going back to the top of the loop.


I have an alternate solution that works with a timer. If the statement changes during the timer, the timer stops and skips the if statements and back up to the beginning.

I think this is what you’re asking for, correct?

1 Like

Yea, that’s what I am looking for.

1 Like

If you want a loop to start another iteration, just add an if statement only for the passable condition. In this case, only check if j has not changed. The other case will automatically fall through and end the scope, thus starting another iteration. In your words, “making a loop return to the beginning”.

The code with a timer that can be interrupted should be something like…

j = 0
while true do
	wait(5)
	if j == 0 then
		local start = tick()
		
		repeat
			wait() -- flippin' precision
		until (tick() - start >= 10) or j == 1
		
		if j == 0 then
			-- code
		end
	end
end
2 Likes

It is unfortunate, but Lua doesn’t have a continue or go-to statement like many other languages. Sometimes nesting if statements like above can become very nasty as they become deep. To combat this, use a function which you can early return from, like so:

local function foo(i)
    if i < 5 then
        return
    end
    -- Do something
    if i == 7 then
        -- skip the rest
        return
    end
    -- additional work
end

for i = 1, 10 do
    foo(i)
end

Note: this converts dangerously deep if statement nesting to sequential early returns.

1 Like

A single run repeat block works too

while true do repeat
  stuff
  if need to skip then
    break
  end
  more stuff
until true end

Just makes a matching subsidiary scope within the while loop to break when you want to continue.