0Pricing
Lua Academy · Lesson

Avoiding Memory Leaks

Common leak patterns in Lua and strategies to prevent them.

What Is a Memory Leak in Lua?

A memory leak occurs when objects accumulate in memory because a reference prevents GC from collecting them, even though the program no longer needs them.

Common Leak: Global Accumulation

Storing objects in a global table without removing them is a classic leak. The global table is always a GC root.

local cache = {}  -- global-like upvalue
function storeResult(key, val)
  cache[key] = val  -- never evicted!
end

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