Replace functions in package.loaded

633 Views Asked by At

How can you replace all the functions for a particular library in package.loaded after a require call?

I've tried to iterate over the relevant table but the table comes up empty.

local aLibrary = require "aLibrary"

for key,value in ipairs(package.loaded.aLibrary) do
    package.loaded.aLibrary[key] = function() end
end
2

There are 2 best solutions below

0
On BEST ANSWER

The simpler code below should do it (but note the use of pairs instead of ipairs).

local aLibrary = require "aLibrary"

for key in pairs(aLibrary) do
    aLibrary[key] = function() end
end

Note that require does not return a copy of the library table and so the code above affects its contents without replacing the library table.

In other words, any later call to require "aLibrary" will return the table with the new functions. If you don't want that to happen, then you probably need a new table instead of changing its contents.

0
On

How about using pairs to go through keys instead of only indices?