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. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.