tags:

views:

101

answers:

1

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.HP
        end
    )
end
+2  A: 

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.

Firas Assaad