在一个函数中对表进行两次排序 - Lua

想要对表格按照 HP 排序,但如果存在重复的 HP,则按照名称排序。当我运行此函数时,它只是将重复的 HP 分组,而没有按照名称排序。

T = { {Name = "Mark", HP = 54, Breed = "Ghost"}, {Name = "Stan", HP = 24, Breed = "Zombie"}, {Name = "Juli", HP = 100, Breed = "Human"}, { HP = 100, Breed = "Human"} }

function(x, y) if x.Name == nil or y.Name == nil then return x.HP < y.HP else return x.Name < y.Name and x.HP < y.HP end end) end

原文链接 https://stackoverflow.com/questions/1656706

点赞
stackoverflow用户148870
stackoverflow用户148870

尝试使用以下排序函数:

function(x, y)
    if x.Name == nil or y.Name == nil then
        return x.HP < y.HP
    else
        return x.HP < y.HP or (x.HP == y.HP and x.Name < y.Name)
    end
end

由于您希望始终将不同的 HP 作为主要排序顺序(其次是名称),因此您希望 HP 检查先出现在 or 子句中,以便,如果它们不同,它将跳过任何其他检查并仅根据 HP 确定。

2009-11-01 09:10:05