for i, v in pairs(Ranks) do
if v.Level then
if User.Level >= v.Level then
for _, userRanks in pairs(User.Ranks) do
if i ~= userRanks then
table.insert(User.Ranks, i)
print(1)
break
end
end
end
end
end
So the idea behind this is, whenever I update a players level, i run the above loop to go through all the Ranks inside the Rank module and see if the player has passed any milestone levels, so they can unlock a new rank. However, when a player hits Level 10, the print(1) prints twice and ends up adding Knight and Peasant to User.Ranks. It should just add the 1 new rank and then stop there. I canât use return as I have further code below this. My thought process was that
if i ~= userRanks then
would mean if they didnât have the rank then add it. The player automatically starts off with Peasant rank in their Ranks table, so it should never be added twice
local userRank;
for num, rank in pairs(Ranks) do
if rank.Level then
if (User.Level >= rank.Level) and (rank.Level > userRank.Level) then
userRank = rank;
end
end
end
-- Their highest rank is now "userRank"
print(userRank.Level)
Whatâs userRank?? I just have a Ranks table, like so
local User = {Ranks = {'Peasants'}}
and then I just want to add in âKnightâ to that table when they hit the specific level. Thereâs more ranks to for different levels, so needs to be able to work with a dozen ranks, not just 2 (which Iâm pretty sure it should work anyway )
But ye, not sure what userRank and thus userRank.Level is in this situation
userRank in this case is the highest achieved rank the user has. If you see under the âWorking code and resultsâ you can see that when I print userRank and userRank.Level it shows the highest rank in the RANKS table.
I chose a bad wording for this situation, my bad! I could have gone with userHighestRank etc.
local UserHighestRank = nil;
local User = {Level = 12};
for rankName, rank in pairs (Ranks) do
if rank.Level then
-- Checking if the user's level is matching this rank's level
-- and if this rank's level is higher than "UserHighestRank" 's level
-- or if it is nil
if ((User.Level >= rank.Level) and (UserHighestRank == nil or UserHighestRank.Level < rank.Level)) then
-- Setting this as the temporary highest rank, so we can check with further ranks
UserHighestRank = rank;
end
end
end
-- Now that the loop is done, we know this is their Highest Rank!
print("User's highest rank:", UserHighestRank.Level)