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

[Solved] How to unpack a dictionary?

Asked by
KarlXYZ 120
9 years ago

I'm trying a script that finds the highest value within a table and prints the value's key from the table.

I've tried using math.max combined with unpack() to get this to work. However, unpack() doesn't like the fact I'm not using an array and gives an error saying 'bad argument #1 to 'max' (number expected, got no value)'.

I have no idea how else I'd do this. The script looks a bit useless as I'm simply using it to see if the whole things works, then I'd make it into a script that's a bit more useful.

local test = {
["low"] = 6,
["mid"] = 10,
["high"] = 16
}

function finder()
local top = math.max(unpack(test))
    for i,v in pairs (test) do
        if v == top then
            print(i)
            break
        end
    end
end

finder()

So if it was working, it should just print "high" to the output. Sorry if I've worded things a bit wrong, I'm trying to make it as understandable as I can.

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

unpack only works for tables that are lists (using 1, 2, 3, so on as its indices).

Instead, you'll have to do the maximum calculation yourself, though it isn't very complicated.

You move through each element and determine whether or not it's bigger than the biggest previously seen. If it is, you remember that place as the biggest so-far-seen element. When there's no more elements to check, you have your answer at the so-far biggest.

function findBiggestIndex( tab )
    -- Since you're using a function, it's better for
    -- the table to search in to be an argument.
    -- That way it's easier to repurpose later.
    biggestIndex = nil;
    for index, value in pairs( tab ) do
        if biggestIndex == nil or tab[ biggestIndex ] < value then
            biggestIndex = index;
        end
    end
    return biggestIndex
end

print( findBiggestIndex( test ))
-- high

For the heck of it, here's a function that will unpack all of the values in a table instead of just the ones in list indices:

function unpackall(tab)
    local o = {};
    for i,v in pairs(tab) do
        table.insert(o,v);
    end
    return unpack(o);
end

Though I think using unpack in general isn't usually a good way to go unless it truly makes the code more elegant (in this case I am not sure that it does -- you still need the second loop anyway)

0
Thanks for the quick answer! :) KarlXYZ 120 — 9y
Ad

Answer this question