Howdy, Stranger!

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

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

Tagged:

Comments

  • dave1707dave1707 Mod
    Posts: 7,555

    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
    
  • dave1707dave1707 Mod
    Posts: 7,555

    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
    
  • Posts: 9

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

Sign In or Register to comment.