Lua sort table alphabetically except numbers

I would like to sort the table alphabetically. Except the rooms.

The code below shows how a table is sorted using the comparator function:

function( a,b ) return aN < bN end 

Gives me:

 obj = { [1] = { ["N"] = "Green 1"; }; [2] = { ["N"] = "Green 11"; }; [3] = { ["N"] = "Green 2"; }; [4] = { ["N"] = "Red 1"; }; } 

But I want it to be sorted as follows:

 obj = { [1] = { ["N"] = "Green 1"; }; [2] = { ["N"] = "Green 2"; }; [3] = { ["N"] = "Green 11"; }; [4] = { ["N"] = "Red 1"; }; } 

Is it possible?

+5
source share
3 answers

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 
+3
source

Try the following:

 local function split(a) local x,y=aN:match("(%S+)%s+(%S+)") return x,tonumber(y) end table.sort(obj, function (a,b) local a1,a2=split(a) local b1,b2=split(b) return a1<b1 or (a1==b1 and a2<b2) end ) 
+6
source

The @lhf solution should work for you, although you may need to consider whether you need to handle corner cases, for example, comparing Green 1 with Green 02 or Green 2 with Green 02. I reviewed several methods for sorting alphanum and compared their results with the message. You can also check out the discussion in the lua email list on this topic.

+3
source

Source: https://habr.com/ru/post/1210933/


All Articles