How do I get the highest integer in a table in Lua?
Asked Answered
T

7

10

How do I get the highest integer in a table in Lua?

Teal answered 3/3, 2011 at 8:3 Comment(0)
F
29

In Lua 5.1 and earlier, you can use

math.max(unpack({1, 2, 3, 4, 5}))

This is limited by the size of the Lua stack; on PUC Lua 5.1, this gets the maximum of up to ca. 8 thousand numbers (if the stack is free, i.e. no function calls have been made yet).

Since Lua 5.2, you must use table.unpack instead of unpack (it has been moved). The stack size has been dramatically increased such that this method can be used to find the maximum of hundreds of thousands of numbers.

Furnishing answered 3/3, 2011 at 11:54 Comment(2)
This will not work for larger tables, as there is a limit for a number of arguments and number of return values in each Lua implementation.Peninsula
Is there a specific amount of arguments allowed in math.max()? It seems like the most "official" way to do things.Teal
B
8

A generic function for achieving this:

function max(t, fn)
    if #t == 0 then return nil, nil end
    local key, value = 1, t[1]
    for i = 2, #t do
        if fn(value, t[i]) then
            key, value = i, t[i]
        end
    end
    return key, value
end

Which is used like this:

print(max({1,2,3,4,1,2,37,1,0}, function(a,b) return a < b end)) --> 7 37
Bradfordbradlee answered 3/3, 2011 at 12:17 Comment(2)
Why is the function called "max", shouldn't it be "compare" or something?Phonation
The function returns the maximum value in the array (and its key), so it makes more sense to call it “max” than “compare”.Hirohito
I
8
loltable = {1, 2, 3, 4, 1, 2, 37, 1, 0}
table.sort(loltable)
print(loltable[#loltable])
Inhumation answered 30/4, 2013 at 10:28 Comment(0)
B
4

The other answer by ponzao is good, but to answer your question more specifically, if you just want to get the highest number (and not the index as well), I usually do this:

function max(a)
  local values = {}

  for k,v in pairs(a) do
    values[#values+1] = v
  end
  table.sort(values) -- automatically sorts lowest to highest

  return values[#values]
end

print(max({1, 2, 3, 4, 1, 2, 37, 1, 0})) --> 37

To take it a step further and include only the array part of the table and filter out for only number values (to prevent errors), you can add some type checks:

function max(a)
  local values = {}

  for k,v in pairs(a) do
    if type(k) == "number" and type(v) == "number" then
      values[#values+1] = v
    end
  end
  table.sort(values) -- automatically sorts lowest to highest

  return values[#values]
end

print(max({1, 2, 3, 4, 1, 2, 37, 1, 0})) --> 37

The logic is as follows:

  1. Create an empty table (array)
  2. Iterate over all keys via pairs (ipairs() stops at first nil, and so does using a for loop with #)
  3. Add each value to the array (after verifying type in second code block)
  4. Sort the array from highest to lowest
  5. Return the value of the last element (after sort, it will be at the end).

I know this is an old question so the OP probably doesn't need this anymore, but this page currently ranks high on Google so hopefully this can help someone else who stumbles upon this page.

Biography answered 16/7, 2015 at 19:44 Comment(1)
Sorting the entire array to get the highest value isn't the most efficient way to do it; most sorting algorithms are O(n log n), meanwhile a simple linear search is O(n).Pricefixing
H
2

If your table is an array (only numeric indices >0) then use table.sort and take t[#t] (however, this changes the table).

Other approach would be like this

m={0,0}
for k,v in pairs(t) do
    if m[1]<v then
         m[1]=v
         m[2]=k
    end
end
print("Maximum of "..m[1].." at index "..m[2])
Huberthuberto answered 3/3, 2011 at 8:19 Comment(7)
Lua table indexes start at 1.Peninsula
That's true and false at the same time. If you do t={"a"}, then t[1] will indeed be "a". But you can start indexing wherever you want, if you just keep in mind that the other indices will end up in the hash part of the table. So t={[0]=0,1,2,3} or even `t={[-123]="a",[-122]="b",'c'} are equally valid. But on those tables the table.sort function won't work, as this only works for arrays with index>0 and no holes.Huberthuberto
shouldn't it be: .." at index " ..m[1]) ?Ronda
Right, And that's probably what Alexander was aiming at too... fixed!Huberthuberto
@jpjacobs, the objection to m[0] is due to the initializer m={0,0} which initialized m[1] and m[2] but not m[0]. That will result in the compare on the third line complaining about comparing and integer with nil.Financier
Right, I see ... Really i've been toying to much with C/C++ lately :p Fixed.Huberthuberto
This solution assumes that only positive values are stored in a table.Longo
R
2

Lua comes with a function to get the highest integer key if thats what you wanted...

table.maxn
Renfroe answered 7/3, 2011 at 7:49 Comment(1)
table.maxn is deprecated as of Lua 5.2.Anklet
R
2

you are forgetting to add table before unpack like this

 local save = math.max(table.unpack({1, 2, 3, 4, 5}))
    print(save)

this should work if you want to find the max or min number

Renaldo answered 18/2, 2022 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.