lua-users home
lua-l archive

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


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/