SortTableNumerically: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
(Blanked the page)
Tag: Blanking
 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{Useful Function}}
__NOTOC__
This function sorts tables by index numerically from largest to smallest or from smallest to largest.
Its also useful for removing gaps from your table.
<br>
'''Important : ONLY WORKS FOR TABLES WITH NUMERIC INDEXES!'''
<br>


==Syntax==
<syntaxhighlight lang="lua">table sortTableNumerically( table theTable, bool fromHighestToLowest = false )</syntaxhighlight>
===Required Arguments===
* '''theTable''': the table you would like to sort.
===Optional Arguments===
* '''fromHighestToLowest''': a bool representing whether the table is to be sorted by index from highest to lowest or lowest to highest.
===Returns===
Returns sorted table.
==Code==
<syntaxhighlight lang="lua">
function sortTableNumerically(theTable, fromHighestToLowest)
    local sortTable = { }
    for k, v in pairs(theTable) do
        table.insert(sortTable, {k, v})
    end
    table.sort(sortTable, function(a,b)
        local result = a[1]<b[1]
        if fromHighestToLowest then
            result = a[1]>b[1]
        end
        return result
    end)
    theTable = {}
    for k,v in ipairs(sortTable) do
        table.insert(theTable, v[2])
    end
    return theTable
end
</syntaxhighlight>
==Example==
The code below will print the table in the correct sorted order.
<syntaxhighlight lang="lua">
function sortTableNumerically(theTable, fromHighestToLowest)
    local sortTable = { }
    for k, v in pairs(theTable) do
        table.insert(sortTable, {k, v})
    end
    table.sort(sortTable, function(a,b)
        local result = a[1]<b[1]
        if fromHighestToLowest then
            result = a[1]>b[1]
        end
        return result
    end)
    theTable = {}
    for k,v in ipairs(sortTable) do
        table.insert(theTable, v[2])
    end
    return theTable
end
local theTable = {[3] = "Dino", [1] = "Doll", [2] = "Car",[6] = "Rattle", [4] = "Dog", [5] = "Boat"}
local sortedTable = sortTableNumerically(theTable, true)
iprint(sortedTable) -- {"Rattle", "Boat", "Dog", "Dino", "Car", "Doll"}
local sortedTable2 = sortTableNumerically(theTable, false)
iprint(sortedTable2) -- {"Doll", "Car", "Dino", "Dog", "Boat", "Rattle"}
local theTable2 = {[3] = "Dino", [1] = "Doll",[6] = "Rattle", [4] = "Dog"}
local sortedTable3 = sortTableNumerically(theTable2, false)
iprint(sortedTable2) -- {"Doll", "Dino", "Dog", "Rattle"}
</syntaxhighlight>
==See Also==
{{Useful_Functions}}

Latest revision as of 07:56, 13 August 2022