Level system can't level up more than once upon receiving a vast quantity of EXP

Hello! I have spent today creating a levelling system and I have come upon an issue where you cannot gain more than one level when your current EXP is greater than the EXP goal (TotalEXP). I will show some of the code then provide a failed solution I tried

function module.ChangeExp(player:Player, amount)
	print("fired")
	local data = DataManager:Get(player)
	if data then
		
		if data.Level >= LevelCap then return end
		
		print("exp changed")
		print(amount)
		print(data.EXP)
		data.EXP += amount*Multiplier
		module.CheckEXP(player)
		module.UpdateUI(player)
		print(data.EXP)
		
		Notifier.LootSignal(amount,0,player)
		
	else
		print("player has no data")
		
	end	
end

-- skipping a lot of lines you don't need to see :)

function module.CheckEXP(player)
	local data = DataManager:Get(player)
	
	if data then
		
		if data.Level == LevelCap then return end
			
		if data.EXP >= data.TotalEXP then
			local xpnum = data.EXP
			local tnum = data.TotalEXP
			--local oldlvl = data.Level
			local startAMT = xpnum - tnum
			
			if startAMT > tnum then
				--module.CheckEXP(player)
				--module.LevelUp(player)
				--startAMT = 0
				print("hmmm")
			end
			
			data.EXP = startAMT
			data.TotalEXP += 25*data.Level
			module.LevelUp(player)
			module.UpdateUI(player)
			
			if data.Level >= LevelCap then
				data.Level = LevelCap
				data.EXP = 0
			end

		end		
	end
end

The solution I’ve tried for this was to check if the EXP amount was greater than the total EXP and running CheckEXP to hopefully keep levelling until the difference was resolved, however this just ran a a botched recursive function around 4000 times.

Here are some visuals to the issue, I gave myself 1000 EXP which I would have hoped to have found a way to level myself several times to compensate for the excess EXP

Capture

The equation startAMT = xpnum - tnum makes sure that no XP goes to waste upon leveling up. I would also like to add that gaining any more xp after this WILL level you up each time no matter the amount.

Thanks! and let me know if I can provide more details.

3 Likes

You will probably need to use a repeat loop and subtract the required xp to the level from the current xp until there is not enough to advance to the next level each time advancing the level

2 Likes

I would try to use while loop instead of a repetitive function to handle the excess EXP.

1 Like

Thank you! this is the code i wrote and it works wonders, would a small wait be necessary or should it be fine?


			if startAMT > tnum then
				--module.CheckEXP(player)
				--module.LevelUp(player)
				--startAMT = 0
				print("hmmm")
				
				repeat
					
					data.EXP -= data.TotalEXP
					data.TotalEXP += 25
					module.LevelUp(player)
					
					
				until data.EXP <= data.TotalEXP
				
			else
```lua

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