Problem with reloading system

Reloading when the ammo reserve is under 30, causes the ammo reserve to go into negative values and causes addition to go wrong. This is weird way to explain this but I provided a gif on what the problem is.

https://gyazo.com/51c0ff014427922a4084763397b870bc

The ammo reserve is supposed to be subtracted by itself, and the subtracted ammo reserve would be added onto the current ammo count, instead it got subtracted by 30 (the ammo capacity) and it got added onto the current ammo count.

It is really hard to explain this, but maybe I’m just bad at math.

Here is my code:

function gun:Reload()
	if self.Ammo < self.Capacity and not self.Aiming and not self.Shooting and not self.Leaning and not self.Reloading then
		self.Reloading = true
		if self.Ammo <= self.AmmoReserve then
			local calculated = self.Capacity - self.Ammo
			self.Ammo = self.Ammo + calculated
			self.AmmoReserve = self.AmmoReserve - calculated
		else
			self.Reloading = false
		end
	end
	self.Reloading = false
	return self.Ammo
end

self.Capacity refers to the ammo capacity and it is 30.

Any suggestions on how I can remake this?

The issue lies here I think

local calculated = self.Capacity - self.Ammo

When you don’t have enough to fill the clip all the way, this line doesn’t take that into account. A way you could fix this is to make sure that calculated isn’t bigger than AmmoReserve.

local calculated = math.min(self.Capacity - self.Ammo, self.AmmoReserve)

And one other potential issue unless it’s intentional. Why does the clip have to have less than the ammo you have left to be able to be reloaded? This means that if you have 24 in your clip and 3 in your reserve, you can’t get those 3 in by reloading.

if self.Ammo <= self.AmmoReserve then

I would imagine you just want to check that self.AmmoReserve is greater than 0.

Also, this is just me being nitpicky but these lines

            self.Reloading = false
		end
	end
	self.Reloading = false

Do the same thing back to back, meaning you only need the second one.

Oh yeah, I was gonna use self.AmmoCapacity instead.