Sorting/iterating through a table by one of its elements

I’m being really dense here. Say I have a table:

[lua]local event = {}
event[1] = {date = 20120214, location = “UK”, notes = “Other details”}
event[2] = {date = 20110901, location = “USA”, notes = “Other details”}
event[3] = {date = 20120416, location = “Sweden”, notes = “Other details”}[/lua]

How can I either:

a) sort the table by ascending ‘date’ so event[2] becomes event[1] etc etc

b) iterate through the table by ascending ‘date’ so I can display the data in order without sorting the underlying table. [import]uid: 93133 topic_id: 28439 reply_id: 328439[/import]

You mean like this?

(plug and play code)

[code]
local events = {}
events[1] = {date = 20120214, location = “UK”, notes = “Other details”}
events[2] = {date = 20110901, location = “USA”, notes = “Other details”}
events[3] = {date = 20120416, location = “Sweden”, notes = “Other details”}

local function sortByDateLowest(a, b)
return a.date < b.date
end

local function sortByDateHighest(a, b)
return a.date > b.date
end

–Sort by highest
table.sort( events, sortByDateHighest )

print( “results of sorting by highest date” )

for i = 1, #events do
print(events[i].date)
end

print( “---------------------\n” )

–Sort by lowest
table.sort( events, sortByDateLowest )

print( “results of sorting by lowest date” )

for i = 1, #events do
print(events[i].date)
end
[/code] [import]uid: 84637 topic_id: 28439 reply_id: 114804[/import]

Thanks for this Danny, I haven’t had a chance to try it out yet as it’s for a future project but it should help a lot. [import]uid: 93133 topic_id: 28439 reply_id: 115367[/import]