lua-users home
lua-l archive

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


On Oct 19, 2011, at 7:26 PM, Roberto Ierusalimschy wrote:

> For instance (also without the global setting). Something like this:
> 
> function module (name, ...)
>  local env = package.loaded[name]
>  if env == nil then
>    env = {}
>    package.loaded[name] = env
>  end
>  env.NAME = name
>  env.M = env
>  for _, f in ipairs{...} do
>    f(env)
>  end
>  return env
> end

Hehe... I guess we criss-crossed the exact same proposal :))

function module( aName, ... )
   local aModule = package.loaded[ aName ]

   if type( aModule ) ~= 'table' then
       aModule = {}
       aModule._M = aModule
       aModule._NAME = aName
       aModule._PACKAGE = aName:sub( 1, aName:len() - ( aName:reverse():find( '.', 1, true ) or 0 ) )

       package.loaded[ aName ] = aModule

       for anIndex = 1, select( '#', ... ) do
           select( anIndex, ... )( aModule )
       end
   end

   return aModule
end