Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Using all values in a table as arguments for math.min?

Asked by
funyun 958 Moderation Voter
9 years ago

If I wanted to find the smallest value in this array:

{1, 2, 3, 4}

...Could I find some way to use math.min to do that? If not, how else would I be able to do it?

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

Yes.

math.min gives you the smallest of all of its arguments. Normally, you can only give e.g., 2 arguments at a time:

local least = math.min( list[1], list[2] )

But we need to find the least of all of the elements. We can do that with a loop:

local least = list[1]
for i = 2, #list do
    least = math.min(least, list[i])
end

What we're saying here is that

least = min(.... min(min(min(list[1], list[2]), list[3]), list[4]), .... )

But, there's something odd about math.min: if you give it a bunch of arguments, we get the least of all of them, not just the first two (or three, or four, or five... all of them):

print( math.min(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) ) -- 1

But from the variable list, we only have one argument. That's why Lua has the unpack functions -- it turns a list into a sequence of arguments:

local list = {4, 2, 1, 3}
print( math.min( unpack(list) ) )
-- 1
Ad

Answer this question