Getting the highest number from a table

Hello! How can I get the highest number from a table? The table below would be an example.

local test = { 1, 2, 3, 10, 321 }
local greatestNumber = 0
for _, number in ipairs(tableHere) do
    if number > greatestNumber then
        greatestNumber = number
    end
end
3 Likes

Thanks!

30 limit lol sorry

If it’s just an array then there’s math.max, no need to loop. math.max will return the maximum value among the numbers its given, so you can just unpack the table into math.max.

local test = {1, 2, 3, 10, 321}
local highestNumber = math.max(table.unpack(test))
print(highestNumber) --> 321
17 Likes

besides what Colbert suggested, another option is using table.sort()

local test = {1, 10, 321, 2, 3}
table.sort(test)

local highestNumber = test[#test]
print(highestNumber) --> 321

no need for any loops at all really

but that mutates the table. What if you want to preserve the table in its original order?

I said it was another option, never said you should use it

I prefer the way colbert did it anyways, since it doesn’t mess with the table

you would have to save the previous table, I don’t know another way that would work

You could initialize greatestNumber to -math.huge if you want to support negatives

1 Like