Search code examples
luapackagelua-tablelua-5.3

Replace functions in package.loaded


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

Solution

  • 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.