Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the smallest number in a Table with Lua

Tags:

arrays

lua

I'm not great at programming and new to Lua. Can someone help explain the logic of what I should be doing as simply as possible, please? I have a Table populated with values and need to return the min number, in this case -9. I know I need to use the math.min, but am not sure how to use it correctly. This is a simplified version of the code I'm working with but trying to figure out the basics so I can hopefully do the rest myself. Any help is appreciated. Thank you.

e.g.:

local test_1 = {2, 7, -9, 0, 27, 36, 16}

function min()
    print(math.min(test_1))
end

min()
like image 257
user1857403 Avatar asked Oct 20 '25 04:10

user1857403


1 Answers

kikito's solution is limited. It will fail for big tables with many thousand elements as Lua cannot unpack too many values.

Here's the straight forward solution. Traverse over the table and remember the smallest value.

local min = math.huge
for i = 1, #test_1  do
  min = min < test_1[i] and min or test_1[i]
end
print(min)

A bit slower due to function calls

for i,v in ipairs(test_1) do
  min = math.min(min, v)
end
print(min)

Also possible but slow, sort the table ascending. your first element is the minimum.

table.sort(test_1)
print(test_1[1])
like image 152
Piglet Avatar answered Oct 22 '25 19:10

Piglet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!