Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to find category of an integer?

Asked by 6 years ago
Edited 6 years ago

Say I have this 'thing': ( [1] What is the correct term for it?)

local Level = {
    {1,     0,      500},
    {2,     500,    1000},
    {3,     1000,   2000}
}

I also have an IntValue called Exp:

local Exp = Player:WaitForChild("Exp")

[2] How would I 'scan' the table/dictionary/whatever to be able to get Level[?][1] where the Integer is in the range Levels[?][2] < Exp < Levels[?][3] (<-- That's the best way I know how to explain it)

E.g.

Exp = 560

The program would output

print("Level: "..--something)
>>> Level: 2

2 answers

Log in to vote
1
Answered by
DanzLua 2879 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

Hmm, here's a version that would work, i'd go through each one and check if its in between and if so then there's your level

local Level = {
    {1,     0,      500},
    {2,     500,    1000},
    {3,     1000,   2000}
}
local Exp = 560

function FindLevel(exp)
    for _,v in pairs(Level) do
        if exp>=v[2] and exp<v[3] then
            return v[1]
        end
    end
end
print("Level: "..FindLevel(Exp))
0
This works perfectly, thanks! shadow7692 69 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

The correct term for what you are assigning to Level is a "table" (in this case, a "multi-dimensional table", "nested tables", or "table of tables").

There are a few other ways of representing your Level table:

  1. Skip the "min" XP. Assume level 1 starts at 0 XP and only put in your table the maximum. (Alternatively, only store the minimum and skip the maximum -- it depends a bit on what you want to have happen when the player reaches the maximum level).
  2. Use keys/values so that you don't have to do Level[someLevel][1], but can instead do Level[someLevel].MinXP
  3. You really needn't store the Level number if you're willing to make the table index the level number. The resulting table, if you also use point #1, would be Level = {500, 1000, 2000} -- each number represents that maximum XP for that level. ex, Level[1] == 500, so if they have less than 500, they're at level 1.

In either case, you'll want to use a for loop to get the correct level. If you use option 3, the code would look like this:

local Level = {500, 1000, 2000}
function LevelFromXP(xp)
    for i = 1, #Level do
        if xp < Level[i] then return i end
    end
    return #Level + 1 -- or whatever level you want them to have when they have more XP than the last entry in the Level table
end
0
Though this explanation is much more useful, I needed to keep the nested tables. Thank you shadow7692 69 — 6y

Answer this question