lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On May 15, 2006, at 20:33, jdarling@eonclash.com wrote:

Also does anyone know how hard it is to overload/override the default
require's handler?  I'd like to be able to redirect require and
dofile when editing the scripts so that if a modified version exists
in memory it is used over the one on disk.

Assuming you are keeping track of your "edited" file, this should be pretty trivial as far as 'require' goes:

package.loaded[ aModuleName ] = loadstring( aModuleSource )()

Doing the opposite -e.g. reloading a module if its source has changed on disk- is a bit more convoluted as you need to figure out where the module was loaded from and keep track of its time stamp.

Here is a tortuous and probably boggy example, using LuaFileSystem [1] to access a package modification date:

----8<----

require( "lfs" )

local _require = require
local _packages = {}

require = function( aName )
        local aModule = _require( aName )
        local aPackage = _packages[ aName ]

        if type( aModule ) ~= "table" then
                aModule = _G[ aName ]
        end

        if aPackage == nil and type( aModule ) == "table" then
                for aKey, aValue in pairs( aModule ) do
                        if type( aValue ) == "function" then
local someInfo = debug.getinfo( aValue, "S" )
                                local aSource = someInfo.source

if aSource ~= nil and aSource:byte() == 64 then
                                        aPackage = {}
aPackage.source = aSource:sub( 2 ) aPackage.time = lfs.attributes( aPackage.source, "modification" )

                                        _packages[ aName ] = aPackage

                                        break
                                end
                        end
                end
        end

        if aPackage ~= nil then
local aTime = lfs.attributes( aPackage.source, "modification" )

                if aTime > aPackage.time then
                        aPackage.time = aTime
                        package.loaded[ aName ] = nil

                        return require( aName )
                end
        end

        return aModule
end

----8<----


Cheers

--
PA, Onnay Equitursay
http://alt.textdrive.com/


[1] http://www.keplerproject.org/luafilesystem/