For i = x, y not working correctly

i have no idee why this is not working correctly. its supposed to just keep adding till it reaches its maxuim (gunClipCapcity) but it adds an extra for whatever reason?

function reload()
	
	if currentAmmo < _settings.gunClipCapacity then
		
		print("Clip Capacity reload(): "..clipCapacity)
		
		for i = currentAmmo, _settings.gunClipCapacity do
			
			currentAmmo = currentAmmo + 1
			
			-- Fire the RemoteEvent to the client
			ammoEvent:FireAllClients(currentAmmo)

			task.wait(1)

		end
	end
end

im guessing its probally something about the if statment

2 Likes

This is expected behaviour with loops, just add a “-1” and you’ll be good to go.

function reload()
	
	if currentAmmo < _settings.gunClipCapacity-1 then
		
		print("Clip Capacity reload(): "..clipCapacity)
		
		for i = currentAmmo, _settings.gunClipCapacity do
			
			currentAmmo += 1
			
			-- Fire the RemoteEvent to the client
			ammoEvent:FireAllClients(currentAmmo)

			task.wait(1)

		end
	end
end
Explaination?

Let’s say we have x which is 5 and maxX which is 10.

We use a loop like you did to reach maxX, so:

for i = x,maxX do
	x += 1
end

Now let’s count the iterations.
So x - maxX is 5

But while using a loop it calculates an extra one because it basically starts with the first integer so

5,6,7,8,9,10 then we still have to loop once to complete the loop so it adds to 11.

Welll somehow the person below me got the solution. sigh whatever.

2 Likes

for loops will work like that, which is why personally I opt for while loops in situations like these

function reload()
	if currentAmmo < _settings.gunClipCapacity then
		print("Clip Capacity reload(): "..clipCapacity)
		while currentAmmo < _settings.gunClipCapacity do
			currentAmmo = currentAmmo + 1

			-- Fire the RemoteEvent to the client
			ammoEvent:FireAllClients(currentAmmo)

			task.wait(1)
		end
	end
end

6 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.