Lua Cheatsheet

Tables

Use this Lua reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Array-Style Tables

local nums = {10, 20, 30}
print(nums[1])      -- 10; Lua arrays conventionally start at 1
nums[#nums + 1] = 40

#t is reliable for sequences: integer keys 1..n with no nil holes.

Dictionary Tables

local scores = {}
scores["Ada"] = 98
scores["Grace"] = 100
print(scores["Ada"])

Dot syntax is shorthand for string keys that are valid identifiers:

local user = { name = "Ada", score = 98 }
print(user.name)       -- user["name"]
user.score = user.score + 1

Constructors

local a = {1, 2, 3}
local b = {x = 10, y = 20}
local c = {["weird-key"] = true, [1 + 1] = "two"}
local mixed = {"first", name = "Lua", [10] = "ten"}

Iteration

for i, value in ipairs(a) do
  print(i, value)
end

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

pairs order is unspecified. Sort keys yourself when deterministic output matters.

Insert, Remove, Sort, Concat

local t = {"b", "c"}
table.insert(t, 1, "a")   -- insert at index 1
table.insert(t, "d")      -- append
local last = table.remove(t)
table.sort(t)
print(table.concat(t, ","))

Tables as Sets

local seen = {}
seen["lua"] = true
if seen[word] then print("known") end

Tables as Records

local person = {
  name = "Ada",
  email = "ada@example.com",
  active = true,
}

Shallow Copy

local function copy(t)
  local out = {}
  for k, v in pairs(t) do
    out[k] = v
  end
  return out
end

This copies keys and values one level deep. Nested tables are still shared.

Metatables Quick Glance

local mt = {
  __index = function(_, key) return "missing: " .. key end
}
local t = setmetatable({}, mt)
print(t.anything)

Metatables customize behavior such as missing-key lookup, arithmetic, string conversion, and comparisons. They are powerful; keep them explicit.