# Sorting data in tables

I had great help with my last question, so I’m back for more please.

I been reading tutorials on sorting tables (http://www.lua.org/pil/19.3.html) but I can’t make my use case work.

I have two sets of variables
time_n (where n is a number assigned at time of dynamic creation)
name_n (where n is a number assigned at time of dynamic creation)

time_1 is related to name_1 in that they are referring to the same item the user has inputted

What I have been trying to do is sort though the times, to list the times in numerical order with the related name as well.

Some example data

``````time_1 = 10
time_2 = 5
time_3 = 45

name_2 = Centennial
name_3 = Pacifica
``````

The resulting list should appear like

``````pacifica 45
centennial 5
``````

When I sort I need to keep the key reference of the times the same, so I can then refer to the name. I have tried putting my key,value pair into another table, but I’m getting very lost.

Can anyone suggest some methods for achieving this please.
Thanks

``````
--# Main
-- test sort

function setup()
t={ {name="a", time=1},{name="b", time=10},{name="c", time=5} }
print("before sorting")
for i,v in ipairs(t) do print( v.name .." " ..tostring(v.time)) end
comp = function(a,b) return (a.time>b.time) end
table.sort(t,comp)
print("after sorting")
for i,v in ipairs(t) do print( v.name .." " ..tostring(v.time)) end
end

``````

avoid the _1, _2 etc, just make table elements that are small tables as above

@Jmv38 got there just before me.

``````tab={}
tab[2]={time=5,name="Centennial"}
tab[3]={time=45,name="Pacifica"}

table.sort(tab,
function(a,b)
return (a.time>b.time)
end)

for k,v in ipairs(tab) do
print(v.name.." "..v.time)
end
``````

if you need explanation just ask.

@Coder sorry for that! But this is because you did a better job: you took the time to copy his data, while i was too lazy to…