Sorting values of the table from largest to smallest

Hello
I have a problem with the sorting of a table by using a function. I tried to create a function that sorts the contents of the table from the largest to the smallest value. But I failed. So far I have only rarely used tables and I’m slightly awkward in this area. I would very happy if someone can help me.

With kind regards,
Gewis

Here’s a way.

function setup()
    tab={34,23,65,74,12,26}
    
    print("Current table order")
    for x,y in pairs(tab) do
        print(x,y)
    end    
    print()
    
    print("Sorted high to low")
    table.sort(tab,highLow)
    for x,y in pairs(tab) do
        print(x,y)
    end    
    print()
    
    print("Sorted low to high")
    table.sort(tab,lowHigh)
    for x,y in pairs(tab) do
        print(x,y)
    end    
    
end

function highLow(a,b)
    return a>b
end

function lowHigh(a,b)
    return a<b
end

if you don’t want seperate functions, this works.

function setup()
    tab={6,3,9,8,2,1}
    
    table.sort(tab,function(i,j) return(i>j) end)
    
    for a,b in pairs(tab) do
        print(b)
    end
end

@dave1707 Thank you, that is exactly what I was looking for :slight_smile: