lua-users home
lua-l archive

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


Lua list:

While trying to do a nice natural sorting style example for Lua based
on site http://www.davekoelle.com/alphanum.html site, I wasn't verify
satisfied with my example,
does anyone have a better method of splitting a string into table of
strings and numbers, than my chunkString function below. I know I'm
missing some simple string.gmatch way of doing it. Whole example is
included...

Thanks
Andrew


function chunkString(str)
    chunkedString={}
    start=1
    while start < #str do

        pat=(pat=="%D+") and "%d+" or  "%D+"

        -- find all sequence of characters or digits (0-9)
        s_chars,e_chars = string.find(str,pat,start)

        if s_chars == start then
            chunk= string.sub(str,s_chars,e_chars)
            table.insert(chunkedString,
                tonumber(chunk) == nil and chunk or tonumber(chunk))
            start=e_chars+1
        end
    end

    return chunkedString
end -- function


function cmpAlphaNum(a,b)
    achunks=chunkString(a)
    bchunks=chunkString(b)
    for i=1,#achunks do
        if achunks[i] < bchunks[i] then
            return true
       end
    end
    return false
end

function table.copy(t)
n={}
for i=1,#t do n[i]=t[i] end
return n
end

unsorted={
"z18.doc","z19.doc","z2.doc","z16.doc","z17.doc","z1.doc","z101.doc","z102.doc","z11.doc","z12.doc",
"z13.doc","z14.doc","z15.doc","z20.doc","z3.doc","z4.doc","z5.doc","z6.doc","z10.doc","z100.doc",
"z7.doc","z8.doc","z9.doc"
}

sortedNormal=table.copy(unsorted)
sortedNatural=table.copy(unsorted)

table.sort(sortedNormal)
table.sort(sortedNatural, cmpAlphaNum)

--
-- print out Unsorted, Normal sort and Natural sort
--
print("Sorting:\n" )
print("Unsorted","Normal", "Natural","\n" )

for i=1,#unsorted do
    print(unsorted[i], sortedNormal[i], sortedNatural[i] )
end