Lua Academy · Lesson

Weak Keys and Weak Values

Create weak tables with __mode='k', 'v', or 'kv' for cache-like structures.

Lesson 2 of 413 steps

Weak Keys and Weak Values is a free Lua Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

What Are Weak Tables?

A weak table holds references that don't prevent garbage collection. Objects in weak tables can be collected even while the table exists.

The __mode Metamethod

Set __mode on the metatable to control weakness: "k" for weak keys, "v" for weak values, "kv" for both.

local weakValues = setmetatable({}, {__mode = "v"})
local weakKeys   = setmetatable({}, {__mode = "k"})

Weak Values Example

A cache where values can be collected when no other references exist.

local cache = setmetatable({}, {__mode = "v"})
local function getObject(key)
  if not cache[key] then
    cache[key] = {data = key}  -- expensive to create
  end
  return cache[key]
end

After GC, Weak Values Disappear

Once the only reference to an object is in a weak-value table, the GC will collect it and the entry disappears.

local t = setmetatable({}, {__mode = "v"})
do
  local obj = {}
  t[1] = obj
  print(t[1])  -- table: 0x...
end
collectgarbage()
print(t[1])  -- nil (collected)

Weak Keys Example

Weak keys let you associate metadata with objects without preventing their collection. When the key object is collected, the entry is removed.

local meta = setmetatable({}, {__mode = "k"})
local function attachMeta(obj, data)
  meta[obj] = data
end

Object Annotation Pattern

Annotate objects with extra data using a weak-key table. When the object is GC'd, the annotation is automatically removed.

local annotations = setmetatable({}, {__mode = "k"})
annotations[myObj] = {created = os.time(), owner = "Alice"}
print(annotations[myObj].owner)

Weak Keys and Value Tables

A "kv" table has both weak keys and values. Only keys that are alive (referenced elsewhere) keep their entries.

Ephemeron Tables

In Lua 5.2+, weak-key tables are ephemerons: if the only reference to the value is through the key, both are collected together. This prevents unexpected retention.

Cache Pattern with Weak Values

The canonical use: a memoization cache that releases cached results when memory is needed, without manual eviction.

local function weakMemo(fn)
  local cache = setmetatable({}, {__mode = "v"})
  return function(x)
    if not cache[x] then cache[x] = fn(x) end
    return cache[x]
  end
end

Limitations

Weak tables cannot hold primitive types (numbers, booleans, strings) as weak values — they cannot be collected by the GC (strings are interned).

When to Use Weak Tables

  • Object caches that should release memory under pressure.
  • Associating metadata with external objects.
  • Implement intern tables for custom objects.

Weak Table Question

What does __mode = "v" on a metatable do?

Recap: Weak Keys and Values

Weak tables use __mode = "k", "v", or "kv" to allow the GC to collect their keys/values. This is essential for memory-safe caches and object annotation patterns.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Weak Keys and Weak Values” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Weak Keys and Weak Values”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “Weak Keys and Weak Values”?

Create weak tables with __mode='k', 'v', or 'kv' for cache-like structures. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Weak Keys and Weak Values” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Lua Garbage Collector Basics
  2. Weak Keys and Weak Values
  3. Finalizers with __gc
  4. Avoiding Memory Leaks
← Back to Lua Academy