tags:

views:

506

answers:

1

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

Questions:

How would I Print just the names?

and

How can I sort it by HP?

+2  A: 

You need to iterate over the table by using either the pairs or ipairs function to print the name. ipairs iterates from 1 to N (numeric indices only), while pairs iterates over every element, in no defined order.

> T = { {Name = "Mark", HP = 54, Breed = "Ghost"}, {Name = "Stan", HP = 24, Breed = "Zombie"}, {Name = "Juli", HP = 100, Breed = "Human"}}
> for _,t in ipairs(T) do print(t.Name) end
Mark
Stan
Juli

Then you can use the table.sort function to sort the table in-place:

> table.sort(T, function(x,y) return x.HP < y.HP end)
> for _,t in ipairs(T) do print(t.Name, t.HP) end
Stan    24
Mark    54
Juli    100

The second argument to table.sort is a comparison function of your choice; in this case, we only wanted to compare the HP values.

Mark Rushakoff
You have reversed the meanings for `ipairs()` and `pairs()`. `ipairs()` iterates the numeric indices, and `pairs()` iterates over every element.
gwell
Oops, thanks for catching that. Fixed.
Mark Rushakoff