For loop skips last iteration

At the moment I’m trying to create a custom animation plugin however I have run into an issue; In my for loop I’m looping from 0,Specified animation length. However the issue with this is that it skips the last iteration (Code below)

local function round(num, numDecimalPlaces)
	local mult = 10^(numDecimalPlaces or 0)
	return math.floor(num * mult + 0.5) / mult
end

local function getDecimals(n)
	if type(n) ~= "number" then return end

	n = tostring(n)

	local _,End = string.find(n,"%.")
	End += 1

	local rest = string.sub(n,End,#n)

	return rest
end
-------------------
self.animationData = {
	["timelineLength"] = 1,
	["timelineIncrement"] = 0.01,
	["required"] = turnNodesIntoRequired(BasisNodes,TargetingNodes),
	["timeline"] = generateEmptyTimeline(TimelineLength),
}
-------------------
for t = 0,self.animationData.timelineLength,self.animationData.timelineIncrement do
	t = round(t,#getDecimals(self.animationData.timelineIncrement))
	t = tostring(t)

	print(t)
end

Output:


(Don’t mind the error that’s from the plugin being run in-game)

Any help is appreciated!

1 Like

Since I don’t know what the correct number of iterations should be, I ran the loop and it turns out to be 100 with the last value t=0.99000000000000000007.

If you expected it to be 101, the latter was not given because adding this value ( t=0.99000000000000000007) the increment makes t greater than 1, so the loop breaks early. Addition (and the other arithmetic operations) of floating numbers has a small inherent error that accumulates and causes this sort of thing.

On the other hand, according to the lua documentation, you should never modify the control variable (i.e. t). This can cause unexpected errors (perhaps the issue you mention). This is in the case where you expected 100 iterations but got 99.

2 Likes

In addition to this, the reason it “skips” the last iteration is because the loop checks if currentStep + step > end. If it’s true then it breaks the loop. What happens is it adds 0.9900000007 to 0.01, which is technically more than 1

1 Like

Alright ill just make my own for loop

1 Like