Get the highest value of an array in Lua

3

I am using Lua code and want to get the largest value of an array. Example:

tem_array = {10,2,3,20,1}

I used this code below, but I get the number of elements and not the maximum:

max = math.max(unpack(tem_array))
    
asked by anonymous 05.02.2015 / 16:12

2 answers

2

The code you posted works as expected.

tem_array = {10, 2, 3, 20, 1}
arraymax = math.max(unpack(tem_array))

print (arraymax) -- 20

DEMO

Another way is to sort the elements through sort() to place the elements in ascending order and pick the last one value.

tem_array = {10, 2, 3, 20, 1}
table.sort(tem_array, function(a,b) return a<b end)

print (tem_array[#tem_array]) -- 20

Or use the default behavior of sort() :

tem_array = {10, 2, 3, 20, 1}
table.sort(tem_array)

print (tem_array[#tem_array]) -- 20

DEMO

    
05.02.2015 / 16:43
0
tem_array = {10,2,3,20,1}
table.sort(tem_array, function(a,b) return a > b end)
print(tem_array[1])
    
24.05.2015 / 02:38