## 1. Purpose

In this post, I will demonstrate how to do common operations with lua array.

## 2. Solution

### 2.1 how to initialize lua array literaly?

``````> x={1,2,3}
> print(x)
1
``````

You can see that lua array index start from 1, not 0.

### 2.2 how to iterate over the lua array?

``````> for _,v in pairs(x) do print(v) end
``````

### 2.3 how to insert elements to lua array?

we can use table.insert to insert element at the end of the array as follows:

``````> table.insert(x,4)
> print(x)
4
``````

table.insert (table, [pos,] value): Inserts an element whose value is value at the specified position (pos) in the array part of the table. The pos parameter is optional and defaults to the end of the array part.

### 2.4 how to remove element from lua array?

We can use table.remove to remove the last element in lua array:

``````> for _,v in pairs(x) do print(v) end
1
2
3
4
> table.remove(x)
> for _,v in pairs(x) do print(v) end
1
2
3
``````

Or you can remove at specified position:

``````> for _,v in pairs(x) do print(v) end
1
2
3
4
> table.remove(x,1)
> for _,v in pairs(x) do print(v) end
2
3
4
``````

we can use `table.getn()` to get the length of a lua array:
``````> print(table.getn(x))