remove()

Published Oct 15, 2023
Contribute to Docs

The remove() function in Lua removes the value of the specified index and clears the index from the table (reducing the length of the table by 1).

Syntax

table.remove(tableName,pos)

remove() returns the value that was removed from the tableName. The pos parameter has a default value of n, which is the length of the table. This causes the last element of the table to be removed if the pos parameter is not provided.

Example

In the following example remove() is used to remove the element at the pos position from the table. This causes other elements to shift down.

local fruit = {
"šŸŽ",
"šŸŒ",
"šŸ‡",
"šŸ“",
"šŸ‰"
}
local removedFruit = table.remove(fruit, 2);
print(removedFruit)
print(table.concat(fruit,", "))

This example results in the following output:

šŸŒ
šŸŽ, šŸ‡, šŸ“, šŸ‰

All contributors

Looking to contribute?

Learn Lua on Codecademy