# How to use the Insert function in Lua Programming?

LuaServer Side ProgrammingProgramming

There are cases when we want to insert elements into a table. In Lua, the table library provides functions to insert elements into the table.

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

If there are three arguments passed to the insert function then the second argument denotes the position in the table where we want to insert the element at.

Let’s explore different examples of the insert function.

## Syntax

insert(x,element)
or
insert(x,pos,element)

In the above example, the x represents the table identifier, the pos represents the position at which we want to insert the element at, and lastly the element denotes the value that we want to insert.

## Example

Let’s consider a simple example where we are printing all the values 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

Nothing fancy is happening in the above code, now let’s say we want to insert an element into the above array, the approach is to make use of the insert function that Lua library provides us.

## Example

Consider the example shown below −

Live Demo

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

In the above example, I am calling the insert function three times to insert values 11, 12 and 13 into our array. Now when we iterate over the array using the generic for we should see all the values printing to the terminal.

## Output

1
2
3
4
5
6
7
8
9
10
11
12
13

It’s that simple. Now let’s make use of the insert function that takes three arguments, the third argument (or actually the second one) is the position(index), where we want to insert our element.

## Example

Consider the example shown below −

Live Demo

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

## Output

1
100
2
3
4
5
6
7
8
9
10
Published on 20-Jul-2021 13:26:48