[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: local variables and scope
- From: Kriss <Kriss@...>
- Date: Fri, 26 Aug 2005 01:45:01 +0100
Just to throw in an alternative setup since this stuff although trivial
code is a non trivial design decision and I didn't find much discussion
when I searched for it before implementing.
Essentially I'm doing the same but rather than keeping a table of
allowed globals I'm just using rawset with some sugar.
Creating a table called global that has a __newindex metatable function
that translates into rawset on _G , IE its just sugar for rawset.
So whenever I really want to have the ability to create a global var,
which is obviously not very often I use global.this="that"
Which to my mind reads well since intended global creations are obvious
from reading the source but that's personal preference. Probably because
I'm using a number of lua modules that get loaded and unloaded
changing the available globals during the life of the program.
This is what I'm using and so far it doesn't seem to have any obvious
problems.
---
local g = {
__newindex_lock = function () -- set error function
local mt=getmetatable(_G)
if not mt then
mt={}
setmetatable(_G,mt)
end
mt.__newindex = function(t,i,v)
error("cannot create global variable `"..i.."'",2)
end
end
,
__newindex_unlock = function () -- clear error function
local mt=getmetatable(_G)
if mt then
mt.__newindex = null
end
end
}
setmetatable(g, {
__index=function(t,i) return rawget(_G,i) end,
__newindex=function(t,i,v) rawset(_G,i,v) end,
})
global=g
global.__newindex_lock()
--
Kriss
http://XIXs.com -><- http://www.WetGenes.com