Need help with converting a number into a value from a predetermined table

hello, I am looking for help on making a script that can be fed a number, and then return a value based off that number. Here is an example:

local Table = {
	["Value1"] = 100;
	["Value2"] = 250;
	["Value3"] = 700;
}

local function SortNumber(Num)
	--somehow this function would sort the number provided. I need help on how to do this.
	return Output
end

local Value = SortNumber(134) --this would equal "Value2". I want the function to return the first value it finds higher then the number provided.

local Value_2 = SortNumber(10) --this equals "Value1".

local Value_3 = SortNumber(10000) --this returns nil, because it is higher then the highest value in the table.

hopefully my explanation makes sense. If you have any more questions, feel free to ask me. Thanks in advance!

local function sortNumber(num)
    local max = math.huge
    local output = nil
    for key, value in pairs(table) do
        if value > num and value < max then
            max = value
            output = key
        end
    end
    return output
end

It’s challenging because you can’t loop through dictionaries in order. I think this function I made kind of closes in on the smallest number that is larger than the number provided.
Also, I didn’t test this code, I’m not exactly sure if math.huge can work that way.

1 Like

Use an array with from lowest to highest instead of a dictionary:

local tab = {
    {Value = 100, Return = "Value1"},
    {Value = 200, Return = "Value2"},
    {Value = 300, Return = "Value3"},
} --> lowest to highest

local function sort(x)
    for _, item in ipairs(tab) do
        if item.Value > x then --> if  the value is bigger, return
            return item.Return
        end
    end
    --> returns nil if no matches
end
2 Likes