SortTableNumerically: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
(Blanked the page)
Tag: Blanking
 
(12 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 smallest to largest.
<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 tableToSort = {[3] = "Dino", [1] = "Doll", [2] = "Car",[6] = "Rattle", [4] = "Dog", [5] = "Boat"}
local sortedTable = sortTableNumerically(tableToSort, true)
iprint(sortedTable) -- {"Rattle", "Boat", "Dog", "Dino", "Car", "Doll"}
local sortedTable2 = sortTableNumerically(tableToSort, false)
iprint(sortedTable2) -- {"Doll", "Car", "Dino", "Dog", "Boat", "Rattle"}
</syntaxhighlight>
==See Also==
{{Useful_Functions}}

Latest revision as of 07:56, 13 August 2022