[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Re: math.max**
**From**: Dirk Laurie <dpl@...>
**Date**: Mon, 1 Aug 2011 16:21:43 +0200

On Mon, Aug 01, 2011 at 03:47:08PM +0200, Chris Datfung wrote:
> I have a variable that contains numeric values separated by a comma, e.g.
> Values = "1, 7, 5". I want to figure out which value within that variable is
> the lowest and highest. The math.min and math.max functions seem most
> appropriate except that they wont accept a variable as an argument.
You mean they won't accept a string as argument except when it
can be coerced to to a number.
> Is this possible with the built in math functions or
No
> do I need to parse the variable
Yes
> and compare values with tonumber()?
No
Dirk
~~~~
function arg(s)
-- assumes s contains comma-separated numbers, whitespace allowed
if tonumber(s) then return s end
local t={}
for k in s:gmatch("[^,]+") do t[#t+1]=k end
return table.unpack(t)
end
function max(...)
local m = pcall(math.max,...)
if m then return m end
for _,a in ipairs{...} do
local s = math.max(arg(a))
m = (m and m>=s) or s
end
return m
end
~~~~
print (max(1,'3','1, 7, 5') --> 7