Last Updated: September 19, 2016
· bcnjr5

Automatically free unused lua modules

When you require a module in Lua, a copy is stored in package.loaded.
Even if you aren't going to use the module again, it is accessible globally, preventing garbage collection.

While you can always set the package.loaded entry to nil, why not have that happen automatically, like the rest of Lua's memory management?

The solution is to make the values in package.loaded weak, allowing them to be collected when they aren't used anywhere else:

setmetatable(package.loaded, {__mode = "v"})

Here is a full module that will do that (and more)