lua-users home
lua-l archive

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


On Wed, Oct 9, 2013 at 8:14 PM, Andrew Starks <andrew.starks@trms.com> wrote:
> If this approach doesn't contain surprises that I'm not seeing, then I
> believe that it is equivalent to the intent of `module`, and thus I
> can safely ignore the on-coming debate about module. :)

Pretty much so!

Penlight has a useful pattern for modules, which you actually
suggested and implemented ;)

-- mod.lua
local print = print
local _ENV, M = require 'pl.import_into' ()

print(_ENV,M)

function answer ()
    -- all the Penlight modules are available in this environment!
    return pretty.write(utils.split '10 20  30', '')
end

return M

-- testmod.lua
local mod = require 'mod'
print(mod.utils, mod.answer)

$ lua52 testmod.lua
table: 000000000051CD80 table: 000000000051CD80
table: 0000000000554A10 function: 0000000000568230

Hello, the module is leaking, it has a reference to utils! To get a
'shadow table', pass true to the function returned by
'pl.import_into':

table: 000000000078CF60 table: 000000000078CD80
nil     function: 000000000078F4D0

The module no longer leaks, because the _environment_ of the module is
not the same as the module itself; the module is a 'shadow table' that
gets only the exported functions.

This pattern could be generalized for non-PL applications, obviously.