lua 排序的坑,table.sort()排序不成功

local tbl = {
		[66]= {userid = 66, score = 88, upTime = 30},
		[22]= {userid = 22, score = 66, upTime = 10},
		[55]={userid = 55, score = 66, upTime = 90},
		[33]={userid = 33, score = 99, upTime = 20},
		[99]={userid =99, score = 66, upTime = 80},
		}


	table.sort(tbl,function(a, b)
	local r = false
	local as = tonumber(a.score)
	local bs = tonumber(b.score)
	local au = tonumber(a.upTime)
	local bu = tonumber(b.upTime)
	local ai = tonumber(a.userid)
	local bi = tonumber(b.userid)
	if(as == bs)then
		r = au < bu
	else
		r = as > bs
	return r
	end
	end)

用上面的排序会出乎你的意料,排序失败

解决办法

local tbl = {
		[66]= {userid = 66, score = 88, upTime = 30},
		[22]= {userid = 22, score = 66, upTime = 10},
		[55]={userid = 55, score = 66, upTime = 90},
		[33]={userid = 33, score = 99, upTime = 20},
		[99]={userid =99, score = 66, upTime = 80},
		}
    local newTable ={}
    for k,v in pairs(tbl )do
        table.insert(newTable ,v)
    end

	table.sort(newTable ,function(a, b)
	local r = false
	local as = tonumber(a.score)
	local bs = tonumber(b.score)
	local au = tonumber(a.upTime)
	local bu = tonumber(b.upTime)
	local ai = tonumber(a.userid)
	local bi = tonumber(b.userid)
	if(as == bs)then
		r = au < bu
	else
		r = as > bs
	return r
	end
	end)

 

你可能感兴趣的:(lua,lua,排序算法)