Nicholas Rubin
Nicholas Rubin

Reputation: 327

Lua Max Number Finder

Here is my code for a simple program that finds the largest number in a table, and returns the number and it's index. My problem is that the program isn't working with negatives.

 numbers = {1, 2, 3}

 function largest(t)
   local maxcount = 0
   local maxindex
   for index, value in pairs(t) do
    if value > maxcount then
       maxcount = value
       maxindex = index
     end
   end
   return maxcount, maxindex
 end

 print(largest(numbers))

This piece of code prints out "3 3". The largest number is 3, and it is in the 3rd position. When i set numbers to something like {-1, -2, -3} it returns "0 nil" instead of "-1 1".

Thanks!

Upvotes: 1

Views: 430

Answers (2)

Larry Battle
Larry Battle

Reputation: 9178

Your default values are wrong. They should be

local maxcount = t[1]
local maxindex = 1

You were receiving "0 nil" because

  • maxindex is undefined until the if condition value > maxcount is true.

  • the default maxcount value was 0 and that's bigger than all the negative numbers.

Upvotes: 4

Preet Kukreti
Preet Kukreti

Reputation: 8607

maxcount must be set to a large negative number at start, not zero. try -math.huge

Upvotes: 4

Related Questions