InsertValueBetweenIndexesInTable: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(Created page with "{{Useful Function}} __NOTOC__ This function places the index among other indexes in the table. <br> '''Important : ONLY WORKS FOR TABLES WITH NUMERIC INDEXES!''' <br> ==Syntax== <syntaxhighlight lang="lua">table insertValueBetweenIndexesInTable( table theTable, int index, value )</syntaxhighlight> ===Required Arguments=== * '''theTable''': The table you want the index to be placed on. * '''index''': The index where you want to put the value. * '''value''': The value yo...")
 
(Blanked the page)
Tag: Blanking
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
{{Useful Function}}
__NOTOC__
This function places the index among other indexes in the table.
<br>
'''Important : ONLY WORKS FOR TABLES WITH NUMERIC INDEXES!'''
<br>


==Syntax==
<syntaxhighlight lang="lua">table insertValueBetweenIndexesInTable( table theTable, int index, value )</syntaxhighlight>
===Required Arguments===
* '''theTable''': The table you want the index to be placed on.
* '''index''': The index where you want to put the value.
* '''value''': The value you want to put in the selected index.
===Returns===
Returns indexed table.
==Code==
<syntaxhighlight lang="lua">
function insertValueBetweenIndexesInTable(theTable, index, value)
    local otherValues = {}
    for k,v in ipairs(theTable) do
        if k >= index then
            otherValues[k+1] = v
            theTable[k] = nil
        end
    end
    for k,v in pairs(otherValues) do
        theTable[k] = v
    end
    theTable[index] = value
    return theTable
end
</syntaxhighlight>
==Example==
The code below prints table with an index placed between other indexes.
<syntaxhighlight lang="lua">
function insertValueBetweenIndexesInTable(theTable, index, value)
    local otherValues = {}
    for k,v in ipairs(theTable) do
        if k >= index then
            otherValues[k+1] = v
            theTable[k] = nil
        end
    end
    for k,v in pairs(otherValues) do
        theTable[k] = v
    end
    theTable[index] = value
    return theTable
end
local theTable = {
    [1] = "Apple",
    [2] = "Peach",
    [3] = "Banana",
    [4] = "Grape",
}
local indexedTable = insertValueBetweenIndexesInTable(theTable, 3, "Orange")
iprint(indexedTable) -- {"Apple", "Peach", "Orange", "Banana", "Grape"}
</syntaxhighlight>
==See Also==
{{Useful_Functions}}

Latest revision as of 18:30, 18 January 2022