8 9 10 11

Tables

156

In the previous tutorial we've learned that Lua array is a special case of Lua table. Lua table is a key-value map. You can use any type for table key except nil. Even a function or another table can be used as a table key!

You can store values of any type inside a table except nil. Nested tables are also supported.

Basic operations

Constructing an empty table:

t = {}

Constructing a table filled with key-value pairs and accessing their values by keys:

t =
{
    name = "Alice",
    age = 20,
    website = "alice.myblog.com"
}

print(t["name"])
print(t["age"])

Putting additional key-value pairs into an existing table:

t =
{
    name = "Alice",
    age = 20,
    website = "alice.myblog.com"
}

t["email"] = "contact@alice.myblog.com"
t["facebook"] = "https://facebook.com/alice"

Deleting a key-value pair from the table:

t =
{
    name = "Alice",
    age = 20,
    website = "alice.myblog.com"
}

t["website"] = nil

Table size can be obtained with # operator:

print(#t)
Rate this post:
Lesson 10
Share this page:

Learning plan

How to write tail recursion in Lua properly
9. Strings
How to define and work with strings
10. Arrays
How to deal with arrays or lists
11. Tables
Table is a general Lua data structure, it's all about tables