lua-users home
lua-l archive

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


On Sat, Jan 9, 2010 at 1:13 PM, Leo Razoumov <slonik.az@gmail.com> wrote:
> As it was mention in other postings it is very convenient to load a
> chunk just *once* and call it later multiple times with different
> environments to achieve different results. I am not sure whether such
> a trick will work with "in" construct.

debug.setfenv still works as expected in this context:

Lua 5.2.0 (work1)  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> require 'debug'
> fn,e = loadstring 'return a + b'
> debug.setfenv(fn,{a = 1, b = 10})
> = fn()
11

However, (and this is a nasty) there are some tricks you cannot do
with debug.setfenv.

Consider this implementation of David Manura's 'module environment ~=
module table' idea:

-- closed.lua

require 'debug'

return function(mod)

    local env,meta = {_M=mod._M,_NAME=mod._NAME,_PACKAGE=mod._PACKAGE},{}

    env._SELF = env

    meta.__index = _G

    function meta.__newindex(t,key,val)

        rawset(mod,key,val)

        rawset(env,key,val)

    end

    setmetatable(env,meta)

    debug.setfenv(3,env)

end



The idea is that you can declare modules with

module(...,require 'closed')

and they will have a private environment, which is however in sync
with the actual module table.

But, we get:

../lua: ./closed.lua:12: 'setfenv' cannot change environment of given object

I'd be happy if someone could point out the problem: I know
debug.setfenv takes somewhat different arguments. The intent is to
reset the environment for the module chunk.

steve d.