[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua registry, environment, and threads.
- From: steve donovan <steve.j.donovan@...>
- Date: Sat, 9 Jan 2010 13:29:01 +0200
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.
- References:
- Lua registry, environment, and threads., Christian Tellefsen
- Re: Lua registry, environment, and threads., Roberto Ierusalimschy
- Re: Lua registry, environment, and threads., Mark Hamburg
- Re: Lua registry, environment, and threads., Patrick Donnelly
- Re: Lua registry, environment, and threads., Roberto Ierusalimschy
- Re: Lua registry, environment, and threads., Enrico Colombini
- Re: Lua registry, environment, and threads., Roberto Ierusalimschy
- Re: Lua registry, environment, and threads., Edgar Toernig
- Re: Lua registry, environment, and threads., Mark Hamburg
- Re: Lua registry, environment, and threads., Leo Razoumov