.remove()
Published Oct 15, 2023Updated Oct 22, 2024
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)
The .remove()
method removes and returns the element at the specified position pos
from the given table tableName
. If pos
is not provided, it defaults to the length of the table, meaning the last element will be removed by default.
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:
šš, š, š, š
Note: In Lua, indices start from 1. Therefore the banana was removed from the table as it was at index 2.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours