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

[Solved] Number Range in a Table?

I've created a table for a level system

local Levels = {
	
	--XP is the data we are comparing
	[0] = {1,0,10},
	[10] = {2,10,20},
	[20] = {3,20,30},
	[30] = {4,30,40},
	[40] = {5,40,50},
	[50] = {6,50,60},
	[60] = {7,60,70},
	[70] = {8,70,80},
	[80] = {9,80,90},
	[90] = {10,90,100},
	[100] = {11,100,110},
	[110] = {12,110,120},
	[120] = {13,120,130},
	[130] = {14,130,140}
	
}

return Levels

The problem is that when comparing a value that is not in the table, for example 8, it gives a error, what I want to do is to create a range. Example:

local Levels = {

[NumberRange.new ( 0, 10 )] = {1,0,10}, 

--I don't know if NumberRange is compatible with tables but I want to do something similar

So that if the value is 0,1,2,3,4,5,6,7,8,9 or 10, it should return {1,0,10} And the same with the others values.

Can someone tell me a way to do that?

Tell me if you want me to send you the other scripts wich depends on this module script . Thanks in advance

1 answer

✓ Accepted answer

Tables can be indexed by anything. For an explanation of why, see here.

So a fairly intuitive way to do what you're looking for is to just do a linear search through the ranges.

function findLevelData(xp)
    for key, value in pairs(levels) do
        if (key.minimum <= xp) and (key.maximum > xp) then
            return value
        end
    end
    -- We failed to find it
    return false
end

One thing to watch for is that you take care with overlapping ranges. For example, if you have the ranges 0-10 and 10-20, you want to make sure that an XP value is only ever considered a member of one of the ranges.

8 comments

1

Thanks a lot dude!, this is really useful!

0

Also, It works with the key=0 and then it gives the following error ServerScriptService.LevelSystem.LevelSystemAPI:18: attempt to index local 'key' (a number value)

0

Which one is line 18 in your script?

0

Is line 3 in your script

0

Are you doing the ranges, or the [0], [10] thing for indexes?

0

I'm using [0],[10],...

1

Mine was written assuming the NumberRange.new thing.

0

Ok, thank you so much!

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