Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sorting data in tables

edited August 2014 in Questions Posts: 20

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_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.
Thanks

Tagged:

Comments

  • Jmv38Jmv38 Mod
    edited August 2014 Posts: 3,295

    --# 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

  • edited August 2014 Posts: 425

    @Jmv38 got there just before me.

    tab={}
    tab[1]={time=10,name="cascade"}
    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.

  • Jmv38Jmv38 Mod
    Posts: 3,295

    @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....

  • Posts: 425

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

    great minds think alike, yet fools seldom differ
    :)

  • Posts: 20

    Thanks,
    Very simple once pointed out.

Sign In or Register to comment.