For loop not performing action correctly

I am using PartCache for this.

I am trying to make a loop that will loop through a list of waypoints and then position PVInstance indicators position to the PathWaypoint position. However, whenever I do it doesn’t always place the instance. Also, I iterate through the table backwards to avoid issues with returning parts.

This is the function and the loop I use to re-position or hide the part waypoints

local function EditVisiblePath(Cache : PartCache.PartCache, Waypoints : Waypoints, Visible : boolean)
	local VisualWaypoints = Cache.InUse

	for i=((#VisualWaypoints > #Waypoints) and #VisualWaypoints) or #Waypoints,1,-1 do
		if Visible and Waypoints[i] then
			print("Visible")
			local part = VisualWaypoints[i] or Cache:GetPart()

			part.CFrame = CFrame.lookAt(Waypoints[i]["Position"],(Waypoints[i+1] or Waypoints[1])["Position"])
		elseif VisualWaypoints[i] then
			print("Hide")
			Cache:ReturnPart(VisualWaypoints[i])
		end
	end
	print(#VisualWaypoints)
end

If Visible is true it should place a part at every waypoint position, but for some reason it only does for about 88 parts even though it shows that never returns parts. If Visible is false then it should return all the parts back to the cache.

There are 88 parts in this this screenshot when there should be 176.

Screen Shot 2021-05-03 at 9.15.23 AM
Note: The hide print statement is called about 30 seconds later when I actually am returning the parts. It is not unintended behavior.


One last thing, I’m not sure if this is an issue, but this function is wrapped. So when called later in the script it’s called as:

local visPath = coroutine.wrap(EditVisiblePath)
visPath(PartCache, Waypoints, Visible)

Never mind. I fixed this myself using: local part = (i > #Waypoints and VisualWaypoints[i]) or Cache:GetPart().