当前位置 : 主页 > 网络编程 > lua >

排序 – Lua排序表按字母顺序排列,除了数字

来源:互联网 收集:自由互联 发布时间:2021-06-23
我想按字母顺序排序表.除了数字. 下面的代码显示了如何使用比较器函数对表进行排序: function( a,b ) return a.N b.N end 给我: obj = { [1] = { ["N"] = "Green 1"; }; [2] = { ["N"] = "Green 11"; }; [3] = {
我想按字母顺序排序表.除了数字.

下面的代码显示了如何使用比较器函数对表进行排序:

function( a,b ) return a.N < b.N end

给我:

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

但是我希望它像这样排序:

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

可能吗?

本来打算发布这个,但是lhf发布的解决方案回答了你的问题.由于您仍然遇到问题,请尝试以下操作.

local function cmp(a, b)
   a = tostring(a.N)
   b = tostring(b.N)
   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, v.N)
end

打印:

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
网友评论