Howdy, Stranger!

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

In this Discussion

Multi column sort

dave1707dave1707 Mod
in Code Sharing Posts: 9,725

Table.sort works just fine if you want to sort a simple table. But there have been times where I wanted to sort more complex tables on different columns. Here’s some code that shows examples of sorting on 2 different type tables on multiple columns. If you uncomment the mySort at the end of the setup() function, you’ll see the alert error message for no columns passes to mySort.

-- sort by column position

function setup()    
    tab1={}
    table.insert(tab1,{12,56,38})
    table.insert(tab1,{34,32,12})
    table.insert(tab1,{12,56,18})
    table.insert(tab1,{12,76,62})
    table.insert(tab1,{12,56,33})
    table.insert(tab1,{76,27,56})
    table.insert(tab1,{17,58,31})
    table.insert(tab1,{12,16,43})
    table.insert(tab1,{12,56,78})

    mySort(tab1,{2,3})   -- sort tab1 on column 2 then 3.

    print("sort columns 2, 3")
    for a,b in pairs(tab1) do    -- print the sorted table
        print(b[1],b[2],b[3])
    end

    tab2={}
    table.insert(tab2,{c1=12,c2=16,c3=36})
    table.insert(tab2,{c1=34,c2=32,c3=12})
    table.insert(tab2,{c1=12,c2=56,c3=18})
    table.insert(tab2,{c1=12,c2=76,c3=36})
    table.insert(tab2,{c1=12,c2=56,c3=36})
    table.insert(tab2,{c1=76,c2=27,c3=56})
    table.insert(tab2,{c1=17,c2=58,c3=31})
    table.insert(tab2,{c1=12,c2=16,c3=43})
    table.insert(tab2,{c1=12,c2=56,c3=78})

    mySort(tab2,{"c1","c3","c2"})   -- sort tab2 on c1, then c3, then c2.

    print("sort columns 1, 3, 2")
    for a,b in pairs(tab2) do    -- print the sorted table
        print(b.c1,b.c2,b.c3)
    end

    —mySort(tab2)   -- causes error
end

function mySort(...)
    tbl,pos=...
    if pos==nil then
        viewer.alert("No column passed to sort function.")
    else
        table.sort(tbl,
        function(a,b)
            for z=1,#pos do
                if a[pos[z]]<b[pos[z]] then
                    return true
                elseif a[pos[z]]>b[pos[z]] then
                    return false 
                end
            end
        end)
    end
end

Comments

Sign In or Register to comment.