How can I find the greatest number out of a list of numbers?

So I’ve been wondering about an easy way to do this. Basically I want to find the largest number in an array like this.

numbers = {1,2,5,2,7,3,8}

I want it to return the index of the largest number (in this case 7) What would be a good efficient way to do this?

You can do this tell me if you want me to explain:

numbers = {1,2,5,2,7,3,8}

local greatestNumber = 0

for i, v in pairs(numbers) do
    if v > greatestNumber then
        greatestNumber = v
    end
end

local index = table.find(numbers, greatestNumber)
1 Like
local t = {1,2,5,2,7,3,8} --table
table.sort(t) --order table from least to greatest
local highest = t[#t] --get the last item
print(highest) -- 8
1 Like

Another alternative is using:

math.max(unpack(numbers))

This should give you the highest number in your list. However I have been told there is an upper limit to how many values can be in the list, so keep that in mind.

1 Like
numbers = {1,2,5,2,7,3,8}
table.sort(numbers, function(left, right)
	return left > right
end)
print(table.concat(numbers, " "))

If you want the numbers to be sorted in descending order (largest to smallest).

1 Like

You all gave perfect solutions so I gave the solution to the first person even though you all deserved it. Thanks guys!

1 Like