I was going to post this initially, but the solution posted by lhf answered your question. Since you still have problems, try the following:
local function cmp(a, b) a = tostring(aN) b = tostring(bN) local patt = '^(.-)%s*(%d+)$' local _,_, col1, num1 = a:find(patt) local _,_, col2, num2 = b:find(patt) if (col1 and col2) and col1 == col2 then return tonumber(num1) < tonumber(num2) end return a < b end local obj = { { N = '1' }, { N = 'Green1' }, -- works with optional space { N = 'Green' }, -- works when doesn't fit the format { N = 'Sky blue99' }, { N = 'Green 11' }, { N = 'Green 2' }, { N = 'Red 02' }, -- works when has leading zeros { N = 'Red 01' }, -- works with padding spaces { N = 'Sky blue 42' }, -- works with multi-word color names { N = 99 }, -- works with numbers } table.sort(obj, cmp) for i,v in ipairs(obj) do print(i, vN) end
Print
1 1 2 99 3 Green 4 Green1 5 Green 2 6 Green 11 7 Red 01 8 Red 02 9 Sky blue 42 10 Sky blue99
source share