Tables in Lua

Share the page with

Tables in Lua

Under the hood, Lua never makes hidden copies of new tables, like other languages like python 😡

{} is the table constructor in Lua.

For example

print(a["x"]) -- we will get 10
a["y"] -- we will get 20
a[4]="hello world"

A table is always anonymous. There is no fixed relationship between a variable that holds a table and table itself.

b = a -- both b and a point to same data, no separate table.
a=nil --> nullify a, do not worry b is still there
b=nil --> now b is gone, we cannot have table entries now :()

When there is no references to a table/ object, then garbage collector comes and clean the space occupied by that object. In this way, as a user we do not have to worry about the memory leak.

We can also use floating point as key 🐺.

Table constructor

We have already seen the empty table constructor, which is given by a={}. We then added entries to the table using a["x"]=10, or we can use a.x=10.

There is another way to construct the table.

extlibs={"LAPACK95", "BLAS95", "FACE", "PENF"}

the we can access the entries using:

extlibs[1] --> "LAPACK95"
extlibs[4] --> "PENF"

We can also use key-value construct.

a={x=10, y=10, z=20}

then we have

a["x"] --> 10
a.x --> 10

Removing fields of table

a={x=10, y=20, z=30, name="point1"} --> "point1" = nil --> is gone

Insert an element

table.insert(t, 1, 10) --> insert 10 at t[1]
table.insert(t,20) --> insert 20 at t[2]
table.insert(t, "x", 30) --> t["x"] = 30

Removing an element

table.remove(t) --> remove the last element
table.remove(t,1) --> remove first element

Table traversal

We can traverse all key-value pairs in a table with the pairs iterator.

t={x=10, y=20, z=30}
for k, v in pairs(t) do
Share the page with