lua-users home
lua-l archive

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


> Adding a package.noglobal function would be nice, then you could go:
> 
>      module("WalkerAI", package.noglobal)
> 
> This function would remove the namespace from the global 
> table. It would 
> require rewriting of the module function as well, to save the 
> previous 
> value of the namespace. Something like this might work:
> 
> 
>      local _module = module
>      function module(name, ...)
>          local _G = _G
>          local package = package
>          local v = _G[name]
>          _module(name,...)
>          if package.loaded[name].__NOGLOBAL ~= nil then
>              _G[name] = v
>          end
>      end
> 
>      function package.noglobal(m)
>          m.__NOGLOBAL = true
>      end
> 
> How does that look?

As someone said before, this will not work correctly. Try the following,
which works for my purposes:

local _module = module
function module(name, ...)
   -- visibility of _G and package does not change here
   local v = _G[name]	
   local env = getfenv(1)   -- save original fenv of new module function
   _module(name, ...)       -- open a module with the renamed original
function
   setfenv(2, _M)           -- setfenv for declarations inside the new
module
   setfenv(1, env)          -- set back original fenv of new module
function
   -- '_G' and 'package' are again visible
   if package.loaded[name].__NOGLOBAL ~= nil then
	_G[name] = v
   end
end

Personally, I do not regard the global module tables as a conceptual
problem.

Userdefined modules and predefined modules ('string', 'table',
'coroutine', 'debug', 'math', 'os', 'io', 'package', and '_G' if you
like) are treated consistently. Even your code uses module 'package'
without requiring it before. 

My point of view is: A module is a globally unique unit. As soon as it
is loaded (by require, preloaded or predefined) is has a globally unique
name. 

I regard it as a design error, if I happen to build a system that loads
two different modules with the same name. 

Best regards 
Franz-Josef