How to Use the Remove function in Lua programming?


There are cases when we want to remove an element from a table. In Lua, the table library provides functions to remove elements from the table.

The remove function usually takes two arguments, the first argument is usually the name of the table from which we want to remove the element from, and the second argument is the position from which we want to remove the element from.

Let’s explore different examples of the remove function.

Syntax

table.remove(x,pos)

The x in the above example denotes the name of the table from which we want to remove the element from, and the pos identifier in the above syntax is the position(index) from which we want to remove the element.

Example

Now, let’s take a simple example where we print the elements that are present in an array. Consider the example shown below −

 Live Demo

a = {1,2,3,4,5,6,7,8,9,10}
for i,v in ipairs(a) do print(v) end

Output

1
2
3
4
5
6
7
8
9
10

Example

Now consider a case where we want to remove an element at position 2 from the above example, we will make use of table.remove function. Consider the example shown below −

 Live Demo

a = {1,2,3,4,5,6,7,8,9,10}
table.remove(a,2) -- remove
for i,v in ipairs(a) do print(v) end

Output

1
3
4
5
6
7
8
9
10

Example

Let’s consider one more example where we will remove an element from a particular index. Consider the example shown below −

 Live Demo

t = { "the", "quick", "brown", "fox" }
table.remove(t,3)
for i,v in ipairs(t) do print(v) end

Output

the
quick
fox

Updated on: 20-Jul-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements