zdtxsg
Last Updated: September 19, 2016
·
17
· bcnjr5
34be7858e3f706e306a434276bfb4404

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)

Say Thanks
Respond