5

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Lucien S.
  • 5,123
  • 10
  • 52
  • 88

2 Answers2

4

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1
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:

Community
  • 1
  • 1
lincb
  • 622
  • 5
  • 20