lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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 
> do I need to parse the variable 
> and compare values with tonumber()?


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)

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
    return m
print (max(1,'3','1, 7, 5') --> 7