How do I choose the highest number out of a table?

Hey! If I have a table, for example,

 local Table = {
  ["Section1"] = 5,
  ["Section2"] = 25,
  ["Section3"] = 7
}

How can I pick the section that has the biggest number in it?

1 Like

You can compare the numbers, for example
if number > number2 then print("biggest number") end

Now if you have a table you can do
if (table[“1”] > table[“2”]) then
if (table[“3”] > table[“2”]) then
print(“3 is biggest number”)
else
print(“2 is biggest number”)
end
else
if (table[“3”] > table[“1”]) then
print(“3 is biggest number”)
else
print(“1 is biggest number”)
end
end

local getHighestNumber (numbersTable : table) 
   local highestNumber = nil

   for _, n in pairs(numbersTable) do
      if not highestNumber or n > highestNumber then
         highestNumber = n
      end
   end

   return highestNumber
end
2 Likes

thank you, is it ok if i can copy this code?

Yes, then mark this topic as closed, by setting my post as a solution.
Have fun programming!

I could be entirely wrong, but can’t you just use table.sort to get the highest number first then just call the first value of the table? Again, I could be entirely wrong. im not that good with tables, but I try :slight_smile:

Thanks, i think regarding the code is that it seems to only loop once? is there a way to make it loop accordingly to how many values are in the table, in this case there’s 3 (section1, section2, section3) so it can consider all the others?