0Pricing
Lua Academy · Lesson

Weak Keys and Weak Values

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

Weak Keys and Weak Values is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

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

Yes — the full text of “Weak Keys and Weak Values” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

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