Maps in Lua

To create an empty table, you can use {}.

m = {}

Set key/value pairs using typical table[key] = val syntax.

m["k1"] = 7
m["k2"] = 13

Printing a table with print will not show all of its key/value pairs well. We’ll use a loop for that.

for k, v in pairs(m) do
    print(k, v)
end

Get a value for a key with table[key].

v1 = m["k1"]
print("v1:", v1)

If the key doesn’t exist, nil is returned, which can be used to check the presence of a key.

v3 = m["k3"]
print("v3:", v3)

The # operator returns the number of key/value pairs when called on an array (not a generic table). Instead, you can count the pairs manually.

length = 0
for _ in pairs(m) do
    length = length + 1
end
print("len:", length)

To remove key/value pairs from a table, set its value to nil.

m["k2"] = nil
for k, v in pairs(m) do
    print(k, v)
end

To clear all key/value pairs from a table, you can iterate over it and set all values to nil.

for k in pairs(m) do
    m[k] = nil
end
for k, v in pairs(m) do
    print(k, v)
end

You can also declare and initialize a new table with some values in the same line.

n = {foo = 1, bar = 2}
for k, v in pairs(n) do
    print(k, v)
end

If you need to check if two tables are equal, you would typically write a custom function to compare their contents.

function tablesEqual(t1, t2)
    for k, v in pairs(t1) do
        if t2[k] ~= v then
            return false
        end
    end
    for k, v in pairs(t2) do
        if t1[k] ~= v then
            return false
        end
    end
    return true
end

n2 = {foo = 1, bar = 2}
if tablesEqual(n, n2) then
    print("n == n2")
end

Note that tables appear in the form {k = v, k = v} when printed with print.

$ lua maps.lua
k1 7
k2 13
v1: 7
v3: nil
len: 2
k1 7
<empty>
bar 2
foo 1
n == n2