I need some help with exp and leveling

So I’ve reached the stage in my game where I want to be able to calculate how much exp they gained, so if its 3x the max exp it levels the player up 3 times and shows the remaining amount of exp until leveling up again.

I’m not sure if I explained that correctly, so I’ll try to give somewhat of an example as to what I’ve been doing which has been causing lag spikes if a player gains too much exp.

for i = 1,amount,1 do
	local maxExp = lev*150 -- the max exp of each level
	eeexp = eeexp + 1 -- i'm counting the exp + 1
	if eeexp >= maxExp then -- each time the exp hits max it levels up and exp reverts back to 0
		lev = lev + 1
		eeexp = 0
	end
end
			
if exp and level then
	level.Value = lev
	exp.Value = eeexp
end

I know there’s a way to calculate the level just by doing;

level = exp/maxexp

but I don’t understand how I am supposed to get the remaining exp in 1 single equation. I’m also unsure if the math above would even be a solution. I know it’s possible, and less lag spikey so I’m currently trying to do that. Does anyone know what I can do to make this equation happen?

1 Like

you don’t have to do it that way, I don’t think that it’s very efficient. You can just detect if the exp value is full, then level up. And then just set the exp to 0 after you level up. Then you can detect the total exp by multiplying the level by how much exp is needed to level up plus the amount of exp they have right now.
So, you would use:
totalxp = level.Value * amount of exp needed to level up + exp.Value

So generally a good solution to this is to just loop each level until the exp is no longer greater than max experience.

For example:

while xp < maxExp do
    level = level + 1
    xp = xp - maxExp
end
-- the value of xp is now the remaining exp

Your current method of calculating levels doesn’t seem to work very well if the max experience is changing every level, as that means you can’t avoid doing what I did above anyway.

2 Likes