[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: from: Lua Module Function Critiqued
- From: Petite Abeille <petite.abeille@...>
- Date: Wed, 9 Oct 2013 19:36:06 +0200
On Oct 9, 2013, at 8:50 AM, steve donovan <steve.j.donovan@gmail.com> wrote:
> The 5.2 compat module is indeed too simplistic - I found this out when
> trying to pack multiple modules into a single Lua file.
(Deprecating 'module' was rather uncharacteristically shortsighted. Oh, well…)
Now that we are all back busily reinventing that particular wheel with different level of squareness… here is my take:
do
local _ENV = module( 'foo' )
… foo stuff ...
end
do
local _ENV = module( 'bar' )
… bar stuff ...
end
do
local _ENV = module( 'baz' )
… baz stuff ...
end
In other words, each module is defined in a chunk (do… end), with its own _ENV. And that's that. The net effect is the same as 5.1 'module' in term of functionalities.
'module' itself is implemented as follow:
do --8<--
--------------------------------------------------------------------------------
-- Import
--------------------------------------------------------------------------------
local assert = assert
local select = select
local type = type
local package = require( 'package' )
--------------------------------------------------------------------------------
-- Module
--------------------------------------------------------------------------------
local _ENV = {}
_VERSION = '1.0.0'
--------------------------------------------------------------------------------
-- Utilities
--------------------------------------------------------------------------------
local function module( aName, ... )
local aModule = package.loaded[ assert( 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
--------------------------------------------------------------------------------
-- Main
--------------------------------------------------------------------------------
package.loaded.module = module
end -->8--
Sigh...