Question

A simple Lua problem here: how to find the index, or key, of the minimum or maximum number in a given table.

math.max/math.min only gives the actual max or min number, not the key.

Was it helpful?

Solution

Iterate the table, and compare the value with the stored max/min value. Take getting the max as an example(assuming the table is a sequence, i.e, array-like:

local t = {1, 3, 7, 6, 4, 0}

local key, max = 1, t[1]
for k, v in ipairs(t) do
    if t[k] > max then
        key, max = k, v
    end
end

print(key, max)

Output:

3       7

If the table is not a sequence, a little improvement would do:

local t = {four = 4, three = 3, seven = 7, six = 6, one = 1, zero = 0}

local key = next(t)
local max = t[key]

for k, v in pairs(t) do
    if t[k] > max then
        key, max = k, v
    end
end

print(key, max)

In real code, remember to check if the table is empty first.

OTHER TIPS

function maxkey(initialtable)
 local maxval = math.max(unpack(initialtable))
 local inv={}
 for k,v in pairs(initialtable) do
   inv[v]=k
 end
 return inv[maxval]
end

See these SO questions:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top