0Pricing
Lua Academy · Lesson

Weak Keys and Weak Values

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

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"})

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