lua按某些键排序的方法

function sort(list, ...)
	local opts = {...};
	local len = #opts;
	return table.sort(list, function(a, b)
		return comp(a, b, opts, 1, len);				
	end);
end
			
function comp(a, b, opts, i, len)
	if (len >= i) then
		local o = opts[i];
		local k = o[1];
		local asc = o[2] or true;
		if (a[k] < b[k] == asc) then return true end;
		if (a[k] == b[k]) then return comp(a, b, opts, i+1, len) end;
		return false;
	end
	return false;
end
							
							
							
local l = {
	{x=1,y=2,z=1},
	{x=1,y=1,z=4},
	{x=1,y=4,z=3},
	{x=2,y=2,z=6},
	{x=1,y=2,z=3},
	{x=1,y=2,z=3},
	{x=2,y=5,z=3},
	{x=3,y=4,z=3},
	{x=1,y=2,z=6},
	{x=2,y=1,z=3},
	{x=3,y=2,z=3},
								
}
sort(l, {"x",true},{"y",true},{"z",true});
for k,v in ipairs(l) do
        print(k,v.x,v.y,v.z);
end

1	1	1	4
2	1	2	1
3	1	2	3
4	1	2	3
5	1	2	6
6	1	4	3
7	2	1	3
8	2	2	6
9	2	5	3
10	3	2	3
11	3	4	3

非递归版本

function sort(list, ...)
	local opts = {...};
	return table.sort(list, function(a, b)
		for i, v in ipairs(opts) do
			local k = v[1];
			local asc = v[2] or true;
			if (a[k] < b[k] == asc) then return true end;
			if (a[k] ~= b[k]) then return false end;
		end 
		return false;				
	end);
end
posted @ 2022-01-04 14:47  J6`  阅读(128)  评论(0编辑  收藏  举报