[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: modules, require, magic
- From: Hisham <hisham.hm@...>
- Date: Wed, 19 Oct 2011 15:20:21 -0200
On Wed, Oct 19, 2011 at 2:44 PM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>> > If you really want 'module', wouldn't be simpler to use
>> >
>> > _ENV = module(...)
>> >
>> > with a simplified version of 'module'?
>>
>> I assume you would also need to "return _ENV" in the end of the module
>> for this to work, [...]
>
> I do not think so. 'module' might use the same trick (technique?) it
> currently uses, regarding the 'loaded' table.
Well noted. Doing this gets us the following:
-------- begin simplifiedmodule.lua
local lua_libs = {}
for k,v in pairs(package.loaded._G) do
lua_libs[k] = v
end
function module(name)
local mod, env = {}, {}
mod._NAME = name
setmetatable(env, { __index = function(t,k) return rawget(mod, k) or
rawget(lua_libs, k) end, __newindex = mod })
package.loaded[name] = mod
return env
end
-------- end simplifiedmodule.lua
-------- begin simple.lua
_ENV = module("simple")
local function bar()
print("hello")
end
function foo()
bar()
end
-------- end simple.lua
-------- begin usesimple.lua
local simple = require("simple")
simple.foo()
print(simple.print)
print(simple._NAME)
-------- end usesimple.lua
Run it with:
lua52 -e'dofile("simplifiedmodule.lua")' usesimple.lua
Certainly an improvement from handling the module table explicitly
(and no segfaults this time). But having basically the same function
being provided by the loader[1] would obviate the need for explicitly
mentioning _ENV.
[1] https://gist.github.com/1298652
-- Hisham
http://hisham.hm/ - http://luarocks.org/
- References:
- modules, require, magic, Eduardo Ochs
- Re: modules, require, magic, Javier Guerra Giraldez
- Re: modules, require, magic, Petite Abeille
- Re: modules, require, magic, Sam Roberts
- Re: modules, require, magic, David Manura
- Re: modules, require, magic, Hisham
- Re: modules, require, magic, Roberto Ierusalimschy
- Re: modules, require, magic, Fabio Mascarenhas
- Re: modules, require, magic, Roberto Ierusalimschy