Modifying Maps in Lua

Maps can be modified after they are created. Starting from the following map:

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

let's look at modifying existing values in the map. As a saw in the previous section we can access elements in the map by retrieving the key from the map, and also by accessing each key as a property of the map. We can also use either method to assign values to the map:

-- update a value in the table by key

x["b"] = 9

-- update value by property

x.c = 11

print(x["a"]) -- 1
print(x["b"]) -- 9
print(x["c"]) -- 11
print(x["d"]) -- 4

Inserting a value is works the same way: we simply create a new key by assigning a value to it:

-- insert a value in the table

x["e"] = 5

x.f = 6

print(x["a"]) -- 1
print(x["b"]) -- 9
print(x["c"]) -- 11
print(x["d"]) -- 4
print(x["e"]) -- 5
print(x["f"]) -- 6

Removing a value from the map is done by assigning nil to it:

-- remove an item from the map

x.e = nil

print(x["a"]) -- 1
print(x["b"]) -- 9
print(x["c"]) -- 11
print(x["d"]) -- 4
print(x["e"]) -- nil
print(x["f"]) -- 6