XP System Not Working

I have made a XP Level up system but in the Script I made it so When the player levels up, the amount of XP that is required to Level up is subtracted from the XP they have, but the number becomes negative. How do i fix this?
My Script:

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	local Cash = Instance.new("IntValue")
	Cash.Parent = leaderstats
	Cash.Name = "Cash"
	Cash.Value = 0
	local Rank = Instance.new("IntValue")
	Rank.Parent = leaderstats
	Rank.Name = "Rank"
	Rank.Value = 1
	local Exp = Instance.new("IntValue")
	Exp.Parent = plr
	Exp.Name = "Exp"
	Exp.Value = 0
	local RequiredExp = Instance.new("IntValue")
	RequiredExp.Parent = plr
	RequiredExp.Name = "RequiredExp"
	RequiredExp.Value = 50
plr.PlayerGui.MainGUI.StatsHUD.LevelHUD.Bar.Black.Clip:TweenSize(UDim2.new(plr.Exp.Value / plr.RequiredExp.Value, 0, 1, 0))
	Exp.Changed:Connect(function(Changed)
		if Exp.Value >= RequiredExp.Value then
			Exp.Value = Exp.Value - RequiredExp.Value -- Here is were I subtract the XP
			Rank.Value = Rank.Value +1
			RequiredExp.Value = RequiredExp.Value + 50
		end
	end)
end)
```
1 Like

Heya!

Have you tried printing Exp.Value and RequiredExp.Value to check if the number should even become negative?

For a quick workaround you can use the math.max() function:

Exp.Value = math.max(Exp.Value - RequiredExp.Value, 0) -- Avoid the Exp value becoming negative.
1 Like