# Lua - Tables in Tables (Printing and Sorting)

This topic is 3366 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

T = { {Name = "Julie", HP = 54, Breed = "Human"}, {Name = "Scorch", HP = 100, Breed = "Dragon"}, {Name = "Robi", HP = 5, Breed = "Zombie"}} Questions: How would i just print the Names? and How would i sort the it by HP? and if HP is the same, sort it by name also?

##### Share on other sites
Quote:
 Original post by NinjaiRoseHow would i just print the Names?
To iterate over the elements contained in a table, you need to use the ipairs() or the pairs() function. ipairs() iterates over the indices in the table (in ascending order), while pairs() iterates over the keys in the table (in an undefined order).

for i, v in pairs(T) do    print(v.Name)end

Note that v.Name is just syntactic sugar for v["Name"].

Quote:
 Original post by NinjaiRoseHow would i sort the it by HP?and if HP is the same, sort it by name also?
You would define an appropriate sorting predicate and pass it to the table's sort() function:

-- define a custom sorting predicatesort_by_hp = function(a, b)    -- if the HPs are equal, sort by name    if a.HP == b.HP then        return a.Name < b.Name    else        return a.HP < b.HP    endend-- sort the table in-placetable.sort(T, sort_by_hp)-- print names and HPfor i, v in pairs(T) do    print(v.Name, v.HP)end

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 11
• 13
• 9
• 11
• ### Forum Statistics

• Total Topics
634092
• Total Posts
3015447
×