How to find the highest value in a table?

Hello! Im currently trying to create a function that finds the highest number in a table, but I don’t know how to create this type of system if anyone could help me out and maybe explain it to me that would be great!

Thanks for reading:D

3 Likes

You can loop through the table and check if that value is greater than either of the past values.

local numberTable = {10, 8, 5, 0, 1, 18, 27}

local highestnumber = 0

for i, v in pairs(numberTable) do
      local number = tonumber(v)
     if number > highestnumber then
        highestnumber = number
    end
end
print(highestnumber)
12 Likes

Thanks for showing me, I think i understand how it works

1 Like

@XdJackyboiiXd21 beat me w/ the code.

I’ll just add that this assumes the list is not sorted. If you know it is sorted, then you can do a binary search instead to find values. And to get lowest/highest values, just grab the first/last value. That being said, it is not worth sorting a list just to do a binary search or find min/max.

5 Likes

Couldn’t agree more. Sorting the table is NOT the way to implement a min/max function since you would end up using an nlog(n) algorithm for something that can be solved in linear time.

2 Likes

Thanks for the information! Ill probably check dev hub to read more on tables

1 Like

If you are confused at all on how it works feel free to ask and we can explain. Also with any other part about tables.