10

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

0

7 Answers 7

30

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Is there a specific amount of arguments allowed in math.max()? It seems like the most "official" way to do things.
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

2 Comments

Why is the function called "max", shouldn't it be "compare" or something?
The function returns the maximum value in the array (and its key), so it makes more sense to call it “max” than “compare”.
8
loltable = {1, 2, 3, 4, 1, 2, 37, 1, 0}
table.sort(loltable)
print(loltable[#loltable])

Comments

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.

1 Comment

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).
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])

7 Comments

Lua table indexes start at 1.
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.
shouldn't it be: .." at index " ..m[1]) ?
Right, And that's probably what Alexander was aiming at too... fixed!
@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.
|
2

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

table.maxn

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.