lua-users home
lua-l archive

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


On Mon, 02 Aug 2010 08:36:56 -0400, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
It was and still it is up to the developer to choose whether to create
globals. Now the "usual practice" seems so simple that it does not
deserve a helper function. Just write this:

   _ENV = {}
   ...
   return _ENV

While I've personally always returned my modules, this would technically  
change the flow of current module definitions using module, which write  
directly to their package.loaded table. For an example where this semantic  
change would have a noticeable impact, imagine a package that defines only  
a few base functions before loading a helper package (which uses local  
base = require "partially_loaded_module"). With the classic "module"  
style, this would work, as the functions would be loaded from the  
partially-constructed table; with returning, it would fail, as the "base"  
package returned by "require" in the sub-package would be "true".
This is why I propose module(...) remain as a helper function which  
creates and returns the appropriate table in package.loaded as it does  
now, but without changing the environment, so existing 5.1 calls to  
module(...) could be updated with a one-line change:
  module(...)

becomes

  _ENV = module(...)

This would also more easliy allow new flows, such as incremental package creation with explicit member definition:
  local my_module = module(...) --can still reference globals normally

  function my_module.divremainder(base, number)
    return math.floor(number/base), number%base
  end

  local unitizer = require "module_that_uses_divremainder"

--module_that_uses_divremainder makes a few assert() calls on divremainder before --defining its functions - there are other instances where functions would actually --need to be called during instantiation, but it would take too long to describe them
  function my_module.print_ft_and_in(inches)
print(string.format("%i inches is %i' %i\"", inches, unitizer.feet(inches)))
  end

  --no need to return here