Nanfeng

Notes on software development, code, and curious ideas

Working with Tables in Lua

Tables are Lua’s only built-in compound data structure. Keys may be any value except nil and NaN; values may be any Lua value. Tables have identity, so two separate tables with equal fields are not equal by default.

1
2
3
4
5
6
7
8
9
local person = {
name = "Ada",
["active"] = true,
"first array value"
}

print(person.name)
print(person["name"])
print(person[1])

Assigning nil removes a key. Reading a missing key returns nil, so a table cannot distinguish an absent key from one deliberately assigned nil without another representation.

Arrays

1
2
3
4
5
local items = { "a", "b", "c" }
table.insert(items, "d")
local removed = table.remove(items, 2)
table.sort(items)
print(table.concat(items, ", "))

These operations assume an array-like sequence. Repeated insertion or removal at the front shifts elements and is inefficient for queues.

Iteration

1
2
3
4
5
6
7
for index, value in ipairs(items) do
print(index, value)
end

for key, value in pairs(person) do
print(key, value)
end

pairs order is unspecified. ipairs follows consecutive integer keys beginning at 1 and stops at the first missing value.

Copying and comparison

local alias = original creates another reference, not a copy. A shallow copy duplicates top-level fields but shares nested tables. Deep copying needs an explicit policy for cycles, metatables, functions, and userdata.

Raw operations such as rawget, rawset, and rawequal bypass metatable behavior. Use them primarily when implementing proxies or metamethods. For ordinary application code, table access through the normal operators keeps abstractions intact.

+