lua-users home
lua-l archive

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


Message: 8
Date: Wed, 23 Oct 2013 10:12:05 +1100
From: Choonster TheMage <choonster.2010@gmail.com>
Subject: Re: Re-requiring modules
To: Lua mailing list <lua-l@lists.lua.org>
Message-ID:
	<CAMaJWZ+4uEbKqJH=fsxFizko4vogP7V4q9vS__Og0MLzj-5Gzg@mail.gmail.com>
Content-Type: text/plain; charset=ISO-8859-1

On 23 October 2013 09:53, Robert Virding <robert.virding@erlang-solutions.com> wrote:
> Yes, BUT NO. Well it shouldn't work. In the 5.2 manual description of 
> package.loaded it says
>
> "package.loaded
>
> A table used by require to control which modules are already loaded. When you require a module modname and package.loaded[modname] is not false, require simply returns the value stored there.
>
> This variable is only a reference to the real table; assignments to this variable do not change the table used by require."
>
> Which seems to imply that these suggestions should not work. This is why I was asking as otherwise it is easy.
>
> Robert
>
> ----- Original Message -----
>> From: "Luiz Henrique de Figueiredo" <lhf@tecgraf.puc-rio.br>
>>
>> > Is it possible to re-require a module?
>>
>> function rerequire(m)
>>       package.loaded[m] = nil
>>       return require(m)
>> end
>>
>> or if your module sets a global:
>>
>> function rerequire(m)
>>       package.loaded[m] = nil
>>       _G[m] = nil
>>       _G[m] = require(m)
>>       return _G[m]
>> end
>>
>> Search lua-l archive for unrequire. See for instance
>>       http://lua-users.org/lists/lua-l/2012-12/msg00883.html
>>
>>
>

package.loaded is a reference to the table that require looks in, but require has its own reference to it, so setting package.loaded to a different table won't do anything. Changing the contents of that table does affect require.

*************************************

When I may need to change from one 'required' file to another I put an unload function into the file.

myfile.lua:

local M = {}

--[[
    unload()
    
    Force re-initialization of modules when required.
--]]
function M.unload()
    package.loaded.myfile = nil
end

return M



The rest is left to the application that may unload and require at will.

*************************************

Allan Pfalzgraf 
EATON
W126N7250 Flint Drive
Menomonee Falls, WI   53051
tel: 414 449-6872 
fax: 414 449-6616 
AllanPfalzgraf@eaton.com 
www.Eaton.com <http://www.eaton.com/>