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

help with getting greatest valued key or keys of a table?

Asked by 8 years ago

ok so i got this table with the given keys:

local tab = {Blue = 5,Red = 6,Yellow = 10}

i cant figure out a way to iterate over the table and return the highest valued key or keys if two or more were equal to each other, could someone show me how i could do this?

1 answer

Log in to vote
3
Answered by 8 years ago

To iterate through the table, just use a for loop. Once you have done this you can run some if statements to check if the number is more than the first value in the pre-defined greatest value table which should be empty at the start. If it is then it should be put in the table after clearing the table, if the value is the same as the one in the table it should just add the value to the table. Your final code should look something like this:

local tab = {Blue = 5,Red = 6,Yellow = 10}

local greatestVal = {}

for i,v in pairs(tab) do
    if greatestVal[1] ~= nil then
        if v > greatestVal[1] then
            greatestVal = {}
            table.insert(greatestVal,v)
        elseif v == greatestVal[1] then
            table.insert(greatestVal,v)
        end
    else
        table.insert(greatestVal,v)
    end
end

Hope this works for you, if it does please vote up and accept as the answer.

0
You don't really need `greatestVal` to be a list. You'll just have something like `5, 5, 5`. And this doesn't tell you anything about the *keys*. BlueTaslem 18071 — 8y
0
Well, if my answer got accepted and +1ed, I think this is what she wanted, go fight some other battle. You lost this one. General_Scripter 425 — 8y
Ad

Answer this question