Get the highest value of an array in Lua

Asked

Viewed 322 times

3

I’m using Lua code and I want to get the higher 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))
  • 2

    it worked for me: http://ideone.com/ipUIuD

  • You can use an increasing sorting algorithm and take the last element.

2 answers

2


The code posted by you works as expected.

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

print (arraymax) -- 20

DEMO

Another way is to classify the elements through the sort() to place the elements in ascending order and take the last 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 standard behavior of sort():

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

print (tem_array[#tem_array]) -- 20

DEMO

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.