Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 32 ยท Tables

Tables as Arrays and Dictionaries

Learn Lua tables: constructors, 1-based indexing, string keys, the length operator and its holes, and how assigning nil removes a key. Includes runnable stand-ins.

Lua has exactly one data structure: the table. Lists, dictionaries, sets, records, objects, modules and even the global environment are all tables. This is a deliberate design choice. Instead of a dozen container types with a dozen sets of rules, you learn one idea and use it everywhere.

A table maps keys to values. A key can be almost any value (a number, a string, a boolean, another table, a function), with one exception: nil can never be a key. A value can be anything at all. This lesson covers how to create tables, how to use them as arrays and as dictionaries, and the two details that surprise newcomers most: indexes start at 1, and the length operator can be unreliable when a table has holes.

The site cannot run real Lua, so the Lua snippets below are read-only. The runnable editors are stand-ins written in JavaScript that model the same behavior with a Map. They are honest approximations: they show what real Lua would print, but they are not Lua.

One structure, many jobs

Arrays Keys 1, 2, 3 and so on.
Dictionaries String keys like name or age.
Records A bundle of named fields.
Objects Fields plus functions.

They are all the same table underneath.

1 / 2

Creating tables

You build a table with a constructor: curly braces. An empty pair makes an empty table. Values separated by commas become an array. key = value pairs become fields:

LUA
local empty = {}
local colors = {"red", "green", "blue"}
local person = {name = "Ada", age = 36}
local mixed = {"first", answer = 42, "second"}

In mixed, the positional values go to keys 1 and 2 in order, while answer is a named field. You can freely combine both styles in one constructor. A trailing comma or semicolon after the last item is allowed.

When the key is not a plain identifier (it has spaces, starts with a digit, or is computed), put it in square brackets:

LUA
local settings = {
  ["max users"] = 100,
  [10] = "ten",
  [true] = "yes",
}

Arrays start at 1

This is the single most famous Lua rule. The first element of a list lives at index 1, not 0:

LUA
local colors = {"red", "green", "blue"}
print(colors[1])   --> red
print(colors[3])   --> blue
print(colors[0])   --> nil
print(colors[4])   --> nil

Reading a key that does not exist is not an error. It simply gives nil. Index 0 is a perfectly legal key, but the constructor never fills it and the standard library functions ignore it, so you will rarely use it.

The stand-in below keeps a Map and reads keys with a helper that returns nil for missing ones:

JS Stand-in: array indexing from 1

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Fields and the dot syntax

For string keys that look like identifiers, Lua offers a shortcut: t.name means exactly t["name"]. Both read and write the same slot.

LUA
local person = {name = "Ada", age = 36}
print(person.name)        --> Ada
print(person["age"])      --> 36
person.city = "London"    -- adds a new field
person.age = 37           -- replaces an existing one

Assigning to a key that does not exist creates it. There is no need to declare fields in advance. The brackets form is essential when the key lives in a variable, because t.key always means the literal string "key":

LUA
local field = "name"
print(person[field])      --> Ada   (uses the variable's value)
print(person.field)       --> nil   (looks up the string "field")

That last line is a classic mistake. Burn the difference into memory: dot means the literal name, brackets mean the value of the expression.

JS Stand-in: dot versus brackets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Numbers as keys: integers and floats

Lua 5.4 has integer and float number subtypes (see Numbers and the math Library). For table keys they are treated as one: a float key with an exact integer value is converted to the integer. So t[1] and t[1.0] are the same slot. Only floats with a fractional part, like 1.5, stay as floats. NaN cannot be a key.

The length operator and holes

The # operator gives the length of a sequence. A sequence is a table whose positive integer keys run from 1 to some n with no gaps:

LUA
local list = {10, 20, 30}
print(#list)              --> 3
list[#list + 1] = 40      -- append at the end
print(#list)              --> 4

list[#list + 1] = value is the classic append idiom. It works because #list is the index of the last item.

Trouble starts when the table has holes, which are nil values in the middle of the numbered keys. For a table with holes, # may return any border: an index n where t[n] is not nil and t[n + 1] is nil (or 0 for an empty table). Several answers can be valid, and which one you get depends on how the table is laid out in memory:

LUA
local gappy = {1, 2, nil, 4}
print(#gappy)             --> 4  (but 2 would also be a valid border)

Real Lua often prints 4 here, but you must not rely on it. The language only promises that the result is a border. Rules to live by:

  • Build arrays without holes, and fill them in order.
  • Never put nil into the middle of a list to mean "empty". Use false, a sentinel value, or store the count yourself.
  • If you need to know how many items a sparse table has, count them with pairs (see Iterating with pairs and ipairs).

The next stand-in computes the borders of a table so you can see why the length is ambiguous:

JS Stand-in: every valid border of a table

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sequence has exactly one border, so # is reliable. The gappy table has two, so the answer to # is unpredictable by design.

nil removes a key

In Lua, nil means "no value", and a table cannot store it. Assigning nil to a field deletes the key entirely. Reading the key afterward gives nil again, which is why you cannot tell "never set" from "set and removed":

LUA
local person = {name = "Ada", age = 36, city = "London"}
person.city = nil
print(person.city)        --> nil
for k, v in pairs(person) do
  print(k, v)             -- city is gone; order is not guaranteed
end

This also explains the hole problem above: setting list[2] = nil in a three-item list leaves a hole, not an empty slot. To remove an item from a list and close the gap, use table.remove from The table Library.

JS Stand-in: assigning nil deletes the key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Tables are references

A variable holding a table does not hold the table itself, only a reference to it. Assigning it to another variable gives you two names for one table:

LUA
local a = {1, 2, 3}
local b = a
b[1] = 99
print(a[1])               --> 99

Equality of tables compares identity, not contents: {} == {} is false because they are two different tables. Copying is covered in Tables in Practice.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does colors[0] return for local colors = {'red', 'green', 'blue'}?

    Lua arrays start at 1, and the constructor never fills key 0. Reading a missing key is not an error, it just gives nil.
  2. 2. Given local k = 'name' and local t = {name = 'Ada'}, what is t.k?

    The dot form uses the literal name, so t.k looks up the string "k", which does not exist. Use t[k] to use the variable's value.
  3. 3. What happens when you run person.city = nil?

    A table cannot store nil. Assigning nil to a key deletes that key.
  4. 4. Why should you avoid holes in an array?

    With holes there can be several valid borders, and # may return any of them. Only a sequence without gaps has a reliable length.

Summary

  • A table maps keys to values and serves as array, dictionary, record and object.
  • Constructors mix positional values (keys 1, 2, 3, ...) and key = value fields.
  • Array indexes start at 1. A missing key reads as nil.
  • t.name equals t["name"]; use brackets when the key is a variable or not an identifier.
  • # is reliable only for sequences without holes; list[#list + 1] = x appends.
  • Assigning nil deletes a key. Tables are references, and == compares identity.

Next, learn the standard helpers for lists in The table Library.