lua-users home
lua-l archive

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


Dirk Laurie <dirk.laurie@gmail.com> writes:
> Just as Lua is written in "clean C, the common subset of Standard C
> and C++", one can write one's new programs in "clean Lua, the common
> subset of Lua 5.1 and 5.2".  Here is a partial list.
>
> 1. unpack = unpack or table.unpack
> 2. Don't use # or the table library on non-sequences.
> 3. Don't use goto.
> 4. Write modules to return a table containing everything and load them by
>     mymod = require "mymod"
> 5. Load bit32 explicitly if you need it.

6. something about setfenv / getfenv / _ENV


My current personal plan (not terribly well thought-through...):

  * I think my uses of setfenv can just follow the 5.2 module of
    "set the environment at load time," so all I need to do is
    define a function like `loadfileinenv', and use that:

      function loadfileinenv (file, env)
        if setfenv then -- 5.1
          return setfenv (loadfile (file), env)
        else            -- 5.2
          return loadfile (file, nil, env)
        end
      end

  * The only place I use "getfenv" is in the form "getfenv (2)", to
    define functions that modify the caller's environment, like
    "import (MODULE, SYM1, SYM2, ...").

    I guess what I'll do here is change the definitions of these
    functions to take the target environment table as an explicit
    first parameter, for which which callers will almost always pass
    _ENV; in Lua 5.1, _ENV will just be nil, so these functions can
    be defined like:

      function import (env, module, ...)
        if not env then
          env = getfenv (2)   -- Lua 5.1 compatibility
        end
        ... do real work ...
      end

    Callers then just do something like:

      import (_ENV, "funkymodule", 'barf')

    That's a little more annoying for callers, but not too onerous,
    and arguably a little more elegant/flexible.


-Miles


-- 
Apologize, v. To lay the foundation for a future offense.