What is this used for?

How about trying to find out which player is closest to an NPC for attack purposes?
math.min could go through a table of the magnitudes and pick the lowest one.

Or the player with the most money in a competition (math.max) loses an extra amount of cash and the player with the least amount (math.min) gets the cash (not a great example, but y’know).

1 Like

It’s fine. You at least tried to help me. I’m still experimenting with the two.

Okay. I’ve experimented with math.max, and I can say that will probably be my most used method. For math.min, I still need some help. How would I print the smallest of the prices?

local Prices = {1, 23, 50, 98, 100, 29}
	
	for i, Price in ipairs(Prices) do
		print(math.min(0, 0)) -- What do I put here?
	end

You’d do it like this

local Prices = {1, 23, 50, 98, 100, 29}

local value = math.min(unpack(Prices))
print(value)

1 Like

Thanks a bunch. That helped me out a lot. I wish I could give all of you the solution just for helping me, but choosing who solved the problem sadly isn’t multiple choice. :pensive:

Thank you all for helping me. :D

1 Like

If it helps you, here are the equivalent functions of min, max, and clamp(which are related in the sense that they limit numbers). For simplicity’s sake, all error handling the original functions have is ignored:

local function helper(t: {number}, isMin: boolean): number
	local y = math.huge*(isMin and 1 or -1)
	for _, v in pairs(t) do
		if isMin and v < y or not isMin and v > y then
			y = v
		end
	end
	return y
end

local function min(x: number, ...: number): number
	return helper({x, ...}, true)
end

local function max(x: number, ...: number): number
	return helper({x, ...}, false)
end

local function clamp(x: number, min: number, max: number): number
	return x < min and min or x > max and max or x
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.