Calculate Levels gained without loop

I’m making a level system and am using a common formula:

25*lvl*(1+lvl)

This formula would increase xp cap every level like this:

Levels    -    XpCap
1         :    50
2         :    150
3         :    300
4         :    500
5         :    750

and so on

while it does give the xp cap for each level there may be a moment where the player gains xp that will level them up more than once instantly and the calculation I do is a loop which for some reason slows the server down, since im not good at math I can’t figure out how to get their new level in one formula.

calculation:

function module:AddXp(amount)
	if not self.Player then return end
	spawn(function()
		self.Xp += amount
		local levelsIncreased = 0
		while self.Xp >= self.XpCap do
			levelsIncreased += 1
			self.Xp -= self.XpCap
			self.XpCap = 25*self.Level*(1+self.Level)
			self.Level += 1
		end

		remotes.Functions.Xp:InvokeClient(self.Player, self.Xp, levelsIncreased)
	end)
end

Was wondering how I would calculate how much levels they earned and how much xp they have left without a loop since it slows server down a lot.

2 Likes

Loops shouldn’t create much noticeable lag if done correctly, Try swapping lines 9 and 10?

Additionally, since you’re not using the return result from the RemoteFunction, consider changing to a RemoteEvent so the code doesn’t yield and the spawn(function() is no longer needed

2 Likes

The delay seemed to have been the InvokeClient, forgot it yielded. Thanks! Thought the delay was from the loop.

2 Likes

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