[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: In praise of globals
- From: Steve Litt <slitt@...>
- Date: Wed, 17 Apr 2013 20:43:32 -0400
On Wed, 17 Apr 2013 22:42:38 +0200
Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2013/4/17 Steve Litt <slitt@troubleshooters.com>:
>
>
> > Is there any way to protect every last bit of _ENV? If so, I could
> > run the program and see every place where a global is being set.
>
> Sure, see Programming in Lua by Roberto Ierusalimschy,
>
> 13.4.4 – Tracking Table Accesses.
>
> http://www.lua.org/pil/13.4.4.html
Thanks Dirk,
That didn't work out quite as well as I'd hoped. It works just fine
with a global table named t, but when I change it to _G, it doesn't
work. Here's the program:
#!/usr/bin/lua
globalfname='Steve'
globallname='Litt'
-- keep a private access to original table
local _forbidden = _G
-- create proxy
_G = {}
-- create metatable
local mt = {
__index = function (_G,k)
print("*access to element " .. tostring(k))
return _forbidden[k] -- access the original table
end,
__newindex = function (_G,k,v)
print("*update of element " .. tostring(k) ..
" to " .. tostring(v))
_forbidden[k] = v -- update original table
end
}
setmetatable(_G, mt)
print('1=====================')
print(globalfname)
print(globallname)
print(garbage)
print('2=====================')
globalfname = 'Stephano'
globallname = 'Littatto'
garbage = 'Basura'
print('3=====================')
print(globalfname)
print(globallname)
print(garbage)
print('4=====================')
for k, v in pairs(_G) do
print(k, ':', v)
print " "
end
print('5=====================')
and here's the output:
slitt@mydesk:~$ ./testglobals.lua
1=====================
Steve
Litt
nil
2=====================
3=====================
Stephano
Littatto
Basura
4=====================
5=====================
slitt@mydesk:~$
You don't see the metatable side-effects when working with _G.
Thanks,
SteveT
Steve Litt * http://www.troubleshooters.com/
Troubleshooting Training * Human Performance