Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to find category of an integer?

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

✓ Accepted answer

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))

1 comment

0

This works perfectly, thanks!

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

1 comment

0

Though this explanation is much more useful, I needed to keep the nested tables. Thank you

This discussion is preserved as it was. New answers, comments, and votes are closed.