lua-users home
lua-l archive

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

On Mon, Feb 16, 2009 at 1:04 AM, Mark Hamburg wrote:
> how about introducing better mechanisms for manipulating function
> environments (which would better support John's scope system in Lua Gems)?
> ...
> But examples
> like John's which save and restore the environment seem fraught with danger.

I've come to a similar conclusion in [1-2] and elsewhere.  Environment
tricks seem to permit some desirable syntax extensions, but the
semantics are not the intended one, and there are obscure corner cases
that break, particularly when saving/restoring them at run-time or
using multiple environments within the same file.  This complicates
the understanding and validation of the code.  For example,

  local on_exit = false -- some variable of the same name (conflict)
  function test()
    -- Lua Programming Gems 13 style scope manager, which creates a local
    -- environment containing the "on_exit" function.
      on_exit(function() print 'success' end)

Here, some local variable "on_exit" far away overrides the environment
variable of the same name in the scope handler block, thereby breaking
the code.  We'd prefer the "on_exit" inside the scope handler to
behave more like a lexical.  You might have noticed that my previous
example that "basically has the same syntax as John's Lua Programming
Gem #13" avoids the problem by passing the table containing on_exit as
an argument rather than as an environment.  The problem here may be
rare, but I think this trade-off of syntax (three less characters)
over conceptual integrity[3] is not in the style of Lua.  (Well,
sometimes it is[2], but that could be improved :) )

There are ways (via patching or Metalua[1]) to make the above work
more consistently, such as by introducing a essentially a new type of
scope that behaves like the environment scope but takes precedence
over locals defined outside of the scope.  Whether this is that
useful, I'm not sure.