Jump to content
  • Advertisement
Sign in to follow this  

Lua - Tables in Tables (Printing and Sorting)

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by NinjaiRose
How 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 NinjaiRose
How 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 predicate
sort_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
end
end

-- sort the table in-place
table.sort(T, sort_by_hp)

-- print names and HP
for i, v in pairs(T) do
print(v.Name, v.HP)
end

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!