What does the code do and what are you not satisfied with?
The code below returns the level from the total exp in which it returns me the level based on the algorithm made.
What potential improvements have you considered?
I feel like it’s better to save some time execution in case their levels are in the 100s which requires more execution.
How (specifically) do you want to improve the code?
I want to be able to determine a single formula that does the same method as below (unless if it is impossible to do so)
-- Assume you have 7 total exp
-- At Level 0, you need 1 exp for Level 1
-- 7 total exp - 1 required exp = 6 remaining Exp
-- Continue the loop until you do not have enough remaining exp for the next level
-- Expected: 7-1=6-2=4-3=1 remaining exp, Current Level = 3
local Total_Exp = player:GetAttribute("Experience")
local Level = 0
while Total_Exp > Level + 1 do
Level += 1
Total_Exp -= Level + 1
end
return Level, Total_Exp -- Total_Exp is the remaining Exp
--[[
We know that sum of n natural numbers is n(n+1)/2
So n² + n <= 2e where e is exp
n² + n - 2e <= 0
Solve the quadratic
n is range [-1 - √(1+8e)/2, -1 + √(1+8e)/2)
Get the largest integer value of n. This will give you the level.
]]
local function getlevel(exp)
return math.floor( (-1 + math.sqrt(1 + 8 * e)) / 2 )
end
I also want to add that since I was asking for Exp Remain as well, I figured you could subtract the exp required from the total exp:
local function GetExpFromLevel(Level: number)
return (Level*(Level+1))/2
end
local function GetExpUntilNextLevel(TotalExp: number, NextLevel: number)
return GetExpFromLevel(NextLevel) - TotalExp
end