Creating Maps


Maps, often also called Dictionaries and associative arrays, are data structures that organize elements such that each element can be easily retrieved by its name, or key. Unlike lists maps do not guarantee fixed ordering, values can be assigned to maps in any order, and retrieved in any order.

A map is created by instantiating a table of values, as below:

-- initialize a mapping of key, value pairs

local x = {
    a = 1,
    b = 2,
    c = 3,
    d = 4,
}

Let's try printing the map:

print(x) -- table: 0x59b68bdd9de0

As we saw in lists, when Lua prints a table it displays the type (table) followed by its address in memory, which can be useful in some situations but generally isn't what we want. Inspecting the values of a map requires accessing them individually.

-- access values stored in the table

print(x["a"]) -- 1
print(x["b"]) -- 2
print(x["c"]) -- 3
print(x["d"]) -- 4

-- accessing values *not* in the table returns nil

print(x["x"]) -- nil

Lua also allows map values to be accessed by referencing map keys as properties:

-- access values stored in the table

print(x.a) -- 1
print(x.b) -- 2
print(x.c) -- 3
print(x.d) -- 4

-- accessing values *not* in the table returns nil

print(x.x) -- nil

There is a second method for creating maps, which is often helpful when creating maps programmatically such as in a loop. In this this method, an empty map is created and assigned to a variable, then values are assigned directly to each key:

-- initialize an empty table

local x = {}

-- assign values to each key

x["a"] = 1
x["b"] = 2
x["c"] = 3
x["d"] = 4

After the map is created, its elements can be accessed as usual:

-- access values stored in the table

print(x["a"]) -- 1
print(x["b"]) -- 2

print(x.c) -- 3
print(x.d) -- 4