Essentially, this system is for a game where the amount of “XP” a user has determines their level. Instead of having to manually bind each level to a certain amount of XP, I have created a system where the nth level’s XP requirement is 2n² + 50n-1:
function LevelModule.getLevels(amountOfLevels)
local levels = {}
for i = 1, amountOfLevels do
local nthLevel = 2*(i^2) + (50*i)-1
levels[i] = nthLevel
end
return levels
end
This works perfectly so far, however are there any improvements I could make? Is this a performant method to achieve what I am trying to do?
This looks like a valid way to calculate the required XP for each level. It appears that you are using a polynomial function to calculate the required XP, which is a common approach to calculating levels in games.
One potential improvement you could make is to add some error handling to your function in case the input is not valid. For example, you may want to check that the value of amountOfLevels is a positive integer before proceeding with the calculation. You could do this by adding a check at the beginning of the function like this:
if type(amountOfLevels) ~= "number" or amountOfLevels % 1 ~= 0 or amountOfLevels < 1 then
error("amountOfLevels must be a positive integer")
end
This will throw an error if the input is not a positive integer, which will help prevent any unexpected behavior in your code.
In terms of performance, this function should be sufficient for most purposes. The time complexity of this function is O(n), which means that the amount of time it takes to run the function will increase linearly with the number of levels. For small values of amountOfLevels , the function should run very quickly. However, if you are expecting to have a very large number of levels (e.g. millions or billions), you may want to consider using a more efficient algorithm to calculate the required XP.