Iterating Over Lua Maps

Iterating over a map done via the pairs function, which produces key, value pairs for each element in the map. Starting from the following map:

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

we can see how this operates using the following loop:

for key, value in pairs(x) do
print(key .. ": " .. value)
end

which produces the following output:

e: 5

d: 4

c: 3

b: 2

a: 1

Note that the order of the output is different than that of the input. Unlike lists, maps do not maintain the order of entries, or have any sense of order at all. In fact, if we iterate over the map again we should expect to process the elements in a different order:

e: 5

a: 1

b: 2

c: 3

d: 4

Keep this in mind when iterating over maps.

When we looked at iterating lists that nil values can create some surprising behaviors. Let's take a quick look at iterating over maps that contain nil values:

x.c = nil

for key, value in pairs(x) do
print(key .. ": " .. value)
end

which produces the result:

d: 4

e: 5

b: 2

a: 1

As we saw in modifying, setting a map value to nil simply removes the key-value pair from the map. As a result, iterating over a map using pairs behaves as expected.