Index randomly changing during function

I have a function here that checks the distances between waypoints in a waypoints folder. For some reason, the i value randomly changes midway through the function when it shouldn’t be. what should be “Distance of waypoint 10 to 9” and so on is instead a random number each time. As you can see in the screenshot, some of them work just fine, but then some numbers just break normality. Is there a fix to this?

WeirdScript

	for i=#waypoints, 1, -1 do
		wait()
		print(i)
		
		if waypoints[i-1] then
			local Distance = (waypoints[i].Position - waypoints[i-1].Position).Magnitude
			TotalDistance = TotalDistance + Distance
			print("Distance of waypoint " .. waypoints[i].Name .. " to " .. waypoints[i-1].Name .. " : " .. Distance)
		end
	end

It looks like waypoints was obtained by :GetChildren(). If so, :GetChildren() does not return the children in sorted form. then, before iterating over them, you must sort them with, for example, table.sort.

table.sort(waypoints, function(a,b)
    return tonumber(a.Name) > tonumber(b.Name)
end)
for i=#waypoints, 1, -1 do
	wait()
1 Like

This is definitely helped a ton. Weird how tables don’t sort themselves automatically when being created. Thanks a million for this.