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 ( 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_1 = cascade
name_2 = Centennial
name_3 = Pacifica 

The resulting list should appear like

pacifica 45
cascade 10
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.

--# 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( .." " ..tostring(v.time)) end
    comp = function(a,b) return (a.time>b.time) end
    print("after sorting")
    for i,v in ipairs(t) do print( .." " ..tostring(v.time)) end

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

@Jmv38 got there just before me.


    return (a.time>b.time) 

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

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…

@Jmv38 looking through your code, we gave exactly the same answer.

great minds think alike, yet fools seldom differ

Very simple once pointed out.