others-how to use array in lua?

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])
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])
4

More about table.insert:

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

More about table.remove:

table.remove (table [, pos]) Returns the element of the table array part at position pos. The subsequent elements will be moved forward. The pos parameter is optional and defaults to the length of the table, which is deleted from the last element.

2.5 how to get the length of the array in lua?

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

> print(table.getn(x))

3. Summary

In this post, I demonstrated how to use lua array. That’s it, thanks for your reading.