Home > Back-end >  How to get the smallest number in a Table with Lua
How to get the smallest number in a Table with Lua

Time:09-28

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()

CodePudding user response:

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])

CodePudding user response:

print(math.min(unpack({2,7,-9,27,36,16})))

Explanation:

math.min accepts variadic arguments - if you give it n arguments it will give you the smallest one:

print(math.min(3,2,1))        -- prints 1
print(math.min(3,2,1,0,-1,-2) -- prints -2

In Lua you can have "freestanding coma-separated lists of expressions". Perhaps the easiest way to see them in action is when assigning multiple values to multiple variables:

local x,y,z = 1,2,3 -- 1,2,3 is a comma-separated list of values
print(x) -- prints 1

When passing parameters to a function, the parameters you pass are one of those lists of expressions.

An array-like table like {2, 7, -9, 0, 27, 36, 16} is not the same thing. Instead, it is a list of a single expression of type table. You could make a list of tables by separating them with commas. For example:

local arr1, arr2, arr3 = {2, 7, -9, 0, 27, 36, 16}, {0,1}, {5,6,7}

The unpack function (in some versions of Lua it's inside table.unpack instead) transforms an array-like table into a list of values.

local x,y,z = unpack({1,2,3})
print(x) -- 1

Combining these three things you end up with the 1-liner that I gave you at the beginning:

print(math.min(unpack({2,7,-9,27,36,16})))

EDIT: @Piglet's comment is correct. There is a limit to the number of arguments a function can accept, so my unpack-based solution will fail if the passed table has too many elements. It seems the max number of arguments depends on how you compile Lua, but in general it seems safe to assume that it will work fine for "less than 50". If your table can have more than 50 items, go with his for-based solution instead.

  • Related