SortTableNumerically: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
No edit summary
(Blanked the page)
Tag: Blanking
 
(16 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 theTableToSort, bool fromHighestToLowest = false)</syntaxhighlight>
===Required Arguments===
* '''theTableToSort''': 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(theTableToSort, fromHighestToLowest)
    local sortTable = { }
    for k, v in pairs(theTableToSort) 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)
    theTableToSort = {}
    for k,v in ipairs(sortTable) do
        table.insert(theTableToSort, v[2])
    end
    return theTableToSort
end
</syntaxhighlight>
==Example==
The code below will print the table in the correct sorted order.
<syntaxhighlight lang="lua">
function sortTableNumerically(theTableToSort, fromHighestToLowest)
    local sortTable = { }
    for k, v in pairs(theTableToSort) 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)
    theTableToSort = {}
    for k,v in ipairs(sortTable) do
        table.insert(theTableToSort, v[2])
    end
    return theTableToSort
end
local tables = {[3] = "Dino", [1] = "Doll", [2] = "Car",[6] = "Rattle", [4] = "Dog", [5] = "Boat"}
tables = sortTableNumerically(tables, true)
iprint(tables) -- {"Rattle", "Boat", "Dog", "Dino", "Car", "Doll"}
local tables2 = {[3] = "Dino", [1] = "Doll", [2] = "Car", [5] = "Boat"}
tables2 = sortTableNumerically(tables2, false)
iprint(tables2) -- {"Doll", "Car", "Dino", "Boat"}
</syntaxhighlight>
==See Also==
{{Useful_Functions}}

Latest revision as of 07:56, 13 August 2022