~/Lua Table Quick Guide

Mar 12, 2023


Lua tables are the main data structure for arrays, dictionaries, and objects.

Creating a table Use curly braces to create a table.

1
2
3
local t = {}
local arr = {1, 2, 3}
local dict = {name = "Alex", age = 30}

Accessing values Use square brackets or dot notation.

1
2
print(arr[1])       -- prints 1
print(dict.name)    -- prints "Alex"

Modifying values Add or update entries by assignment.

1
2
t["a"] = 10
t.b = 20

Iterating a table Use pairs for key-value pairs, ipairs for arrays.

1
2
3
4
5
6
7
for k, v in pairs(dict) do
  print(k, v)
end

for i, v in ipairs(arr) do
  print(i, v)
end

Removing values Set the key to nil.

1
dict.age = nil

Table length Use # for array-like tables.

1
print(#arr) -- prints 3

Metatables Tables can have metatables for custom behaviors.

1
2
local mt = {__index = function() return "not found" end}
setmetatable(t, mt)

Lua tables are flexible and serve as building blocks for all data structures. More details at the official Lua manual.

Tags: [lua] [table]