lua-users home
lua-l archive

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


>There are no references from env tables to functions, only the other way around.
Can you explain further please?

I am struggling a little with the following code

local g={}
setfenv(0,setmetatable(g, {__index=_G}))
print("table pointers", g,_G)
a=1
print("value of a", a)
print("value of g.a", g.a)
print("value of _G.a", _G.a)
table.foreach(_G,print)
for k,v in pairs(g)  do print(k,v) end

gives

table pointers  table: 009D6700 table: 009D0270
value of a      1
value of g.a    1
value of _G.a   1
a       1
string  table: 009D3830
xpcall  function: 009D1F40
etc

lua5: t3.lua:9: attempt to call a nil value
stack traceback:
        t3.lua:9: in main chunk
        [C]: ?

All of this works as I would expect until the
for statement. If I use 1 instead of 0 then the
for statement does not fail.

DB

+++++++++++++++++++++++++++++++++
>>function func()
>>  a=1;
>>end
>>
>>g={}
>>setfenv(func, setmetatable(g, {__index=_G}))
>>
>>What is the correct way to tidy up from here?
>>Is it necessary to issue another setfenv() before
>>setting g or func to nil? 
>
>Setting g to nil has no effect on func after the setfenv call.
>I'm not sure what you mean by tidying up. Perhaps it will be clearer if
>you use a local g instead of a global one.
>
>>Is func collectable after setting its value to nil or
>>does the setfenv() continue to reference func()?
>
>There are no references from env tables to functions, only the other way around.
>--lhf