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
1
  • Use indentation to auto-format code samples.
    – outis
    Commented Nov 1, 2009 at 7:53

1 Answer 1

3

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.