Minimum and maximum

Basic types / Numbers / Mathematical operations

local min_value = math.min(2, 1, 3)
-- min_value = 1

-- A table goes through table.unpack: good
-- for a short one, not for a million values
local nums = {2, 1, 3}
local max_value = math.max(table.unpack(nums))
-- max_value = 3

-- No key argument: the longest by a loop
local words = {"one", "three", "two"}
local longest = words[1]
for _, word in ipairs(words) do
  if #word > #longest then
    longest = word
  end
end
-- longest = three

print("min_value = " .. min_value)
print("max_value = " .. max_value)
print("longest = " .. longest)

-- Empty input is an error, there is no default
local ok, err = pcall(math.max,
                      table.unpack({}))
-- ok = false
-- err = bad argument #1 to 'math.max'
-- (value expected)
print("ok = " .. tostring(ok))
print("err = " .. err)