| Message |
The sort function only works on numerically-indexed tables, whereas your tables has keys "peter", "paul" and "mary".
You can sort it, but you must first get a numerically-keyed table. This will do it:
age = {}
age.peter = 24
age.paul = 14
age.mary = 34
-- copy keys into numeric table
t = {}
for k in pairs (age) do
table.insert (t, k) -- remember key of each item
end -- for
-- show unsorted table
table.foreach (t, print)
-- sort it
table.sort (t,
function (a, b)
return age [a] < age [b]
end -- function
)
-- show results
print "after sort..."
table.foreach (t, print)
Output
1 peter
2 mary
3 paul
after sort...
1 paul
2 peter
3 mary
What I have done here is first looped to copy the keys of your main table into a secondary (temporary) table t. You can see from the initial debugging display that they were added in the order peter, mary and paul (they are stored internally as a hash, so the order cannot really be predicted).
Now we sort the table t, using the keys to index into the age table to find which age is less than which other age.
Finally we can print the table t, which is now sorted into the correct order (paul, peter, mary).
This general technique can be used to sort anything into any sequence. |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|