lua-users home
lua-l archive

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


On 26.08.2012 3:37, Paul K wrote:
 I'm not sure if this is by coincidence or not (as it may be just
 treated as the same value, which means that the sort order will be
 arbitrarily picked between 012 and 12), but it should be easy to fix
 the logic if you want a specific order; just add the length:

 function alphanumsort(o)
    local function padnum(d) return
 ("%012d"):format(d)..("%02d"):format(12-#d) end
    table.sort(o, function(a,b)
      return tostring(a):gsub("%d+",padnum)<   tostring(b):gsub("%d+",padnum) end)
    return o
 end

 Use format(12-#d) if you want 012 before 12 or format(#d) if you want
 12 before 012 (this is assuming the length is 12 or less). I'll update
 the blog post to reflect this.


In case of "012b" vs "12a" the second one should be smaller. I'm pretty
confident it's just the case of strings being the same otherwise when
lexicographical order should kick in.
The limitation of 12 characters can't be extended much, surely no more
than 16 characters, I don't remember the actual limit for 'double'.
padnum converts numbers to double and then back to string, so with
numbers too big this won't work due to limited precision. E.g. padnum
will turn "10000000000000001" and "10000000000000000" into the same
number no matter what.

--
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru