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))
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))
The code you posted works as expected.
tem_array = {10, 2, 3, 20, 1}
arraymax = math.max(unpack(tem_array))
print (arraymax) -- 20
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
tem_array = {10,2,3,20,1}
table.sort(tem_array, function(a,b) return a > b end)
print(tem_array[1])