Am I breaking this loop correctly?

I’m currently working on a lerp and trying to figure out if I’m breaking this for loop correctly.
Would this be correct? Im wanting to break the loop so I can start another loop.

local center = game.Workspace.Elevator.PrimaryPart
local lerp1 = game.Workspace.Lerp1

for i = 0, 1, 0.0001 do
	wait()
	center.CFrame = center.CFrame:Lerp(lerp1.CFrame, i)
	if i == 1 then
		break
	end
end
1 Like

That looks about right, is it not working?

It runs as normal but the second loop never starts…

for i = 0, 1, 0.0001 do
	wait()
	center.CFrame = center.CFrame:Lerp(lerp1.CFrame, i)
	if i == 1 then
      break
   end
end


for i = 0, 1, 0.0001 do
	wait()
	center.CFrame = center.CFrame:Lerp(lerp2.CFrame, i)
end

Is it taking too long? Can you add a print() in between them and look at the output?

I checked it and yeah this is taking way to long… I want the loop to end when the lerp ends, but the loop just continues running even when the lerp is done

If the first loop is running for far too long, you may want to change the delta at which you change the cframe with. Your current delta is at 0.001, so try maybe 0.01 and go from there? Here’s an example of what I mean.

local delta = 0.01 -- This is what I was talking about
for i = 0, 1, delta do
    wait() -- I believe the wait also has something to do with the loop taking forever.
    center.CFrame = center.CFrame:Lerp(lerp1.CFrame, i)
    -- I took out the i == 1 statement because it's redundant in this scenario.
end

It’s also worth noting that if you need to cancel a loop, you can do something like this:

local cancelLoop = false

local delta = 0.01 
coroutine.resume(coroutine.create(function()
    for i = 0, 1, delta do
        if cancelLoop then break end -- This is probably why you wanted to break out.
        wait()
        center.CFrame = center.CFrame:Lerp(lerp1.CFrame, i)
    end
end)) -- The code below will run alongside the loop. Check the coroutine docs for more info

. . .

if (someLogic) then -- Say another loop needs to happen right then or something like that
    cancelLoop = true
end

Essentially, the purpose of this is to have the loop check every step whether or not it should continue. If it should continue, do whatever. If not, then cease operation.

iirc wait is the equivalent of wait(0.03), This loop will run 10000 times and each loop will take 0.03 seconds, 0.03 * 10000 is 300, so the loop will take 300 seconds to complete.