table.remove()
The table.remove()
function removes an element from a table at a specified position and shifts the subsequent elements down to fill the gap.
Syntax
table.remove(tableData, position)
Parameters
- Name
tableData
- Type
- table
- Description
The table from which an element will be removed.
- Name
position
- Type
- number
- Description
The position in the table of the element to remove. If omitted, the last element will be removed.
Return
The function returns the value of the removed element. If the table is empty or the specified position is out of range, it returns nil
.
Description
The table.remove()
function is useful for deleting elements from a table and automatically reindexing the remaining elements. This function modifies the original table.
Examples
Removing an element from a specific position
local fruits = {"Apple", "Banana", "Cherry"}
local removedFruit = table.remove(fruits, 2)
print(removedFruit) -- Output: Banana
print(table.concat(fruits, ", ")) -- Output: Apple, Cherry
Removing the last element
local numbers = {1, 2, 3, 4, 5}
local lastNumber = table.remove(numbers)
print(lastNumber) -- Output: 5
print(table.concat(numbers, ", ")) -- Output: 1, 2, 3, 4
Handling out-of-range positions
local emptyTable = {}
local removedElement = table.remove(emptyTable, 1)
print(removedElement) -- Output: nil
See also
table.insert()
: Inserts a value into a table at a specified position.table.move()
: Moves elements within a table, potentially useful for rearranging after removals.