开发者

Sorting Tables - Lua

开发者 https://www.devze.com 2022-12-10 03:21 出处:网络
I am trying to sort but there is a nil.How can i get around this? Code im useing: (sorting it by name and HPs. in case there is duplicate HPs)

I am trying to sort but there is a nil. How can i get around this?

Code im useing: (sorting it by name and HPs. in case there is duplicate HPs)

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

function Sorting(T)
    table.sort(T, 
        function(x,y)
            return x.Name < y.Name and x.HP < y.H开发者_如何学GoP
        end
    )
end


Assuming you want to compare by HP if name isn't available, how about you change the sort comparison function to:

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

Your problem is that Name isn't a real key if it's not available all the time.

0

精彩评论

暂无评论...
验证码 换一张
取 消