Search code examples
dependency-injectionluarequire

Is there a way in lua to define a function that will run if a file is required?


I would like to create a lua function early in a script that will then automatically get called if a matching filename is required but before that require is complete.

effectively it will go

if FILE then
   run before FILE is loaded
end

-- some other stuff

require"FILE"

If FILE is never required then the stuff in the if will never run


Solution

  • require is just a function so you can redefine it.

    $ cat foo.lua
    real_require = require
    
    function require(mod)
        if mod == 'string' then
            -- do something
            print('importing ' .. mod)
        end
    
        return real_require(mod)
    end
    
    require'string'
    $ lua foo.lua
    importing string
    $