luaroblox

Why is Roblox skipping for loops


I have a script that gradually teleports the player to a part:

for y = 0, math.floor((part.Y-player.Y)/steps), 1 do
    wait(0.3)
    print "1"
    game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame = game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame + Vector3.new(0, steps, 0)
end
for x = 0, math.floor((part.X-player.X)/steps), 1 do
    wait(0.3)
    print "2"
    game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame = game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame + Vector3.new(steps, 0, 0)
end
for z = 0, math.floor((part.Z-player.Z)/steps), 1 do
    wait(0.3)
    print "3"
    game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame = game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame + Vector3.new(0, 0, steps)
end

Whenever I run the script on roblox studio it skips the Y for loop and the Z for loop and only runs the X for loop. Any idea why?


Solution

  • As @Egor Skriptunoff said, if the part Y, X or Z values are smaller than the player's Y, X or Z values then the loop will not run.

    An easy way to fix this would be to use the math.abs() method around the subtraction like so,

    for y = 0, math.floor(math.abs(part.Y-player.Y)/steps), 1 do
        wait(0.3)
        print "1"
        game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame = game.Players:FindFirstChild(username).Character.HumanoidRootPart.CFrame + Vector3.new(0, steps, 0)
    end
    

    This makes sure that the result will always be positive as math.abs just gets rid of the negative symbol.