lua-users home
lua-l archive

Say no to global by default?

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


I have not read all the correspondence on the
"Say no to globals by default thread" so it could be that
this is redundant. In the latest version of RiscLua I
have a prelude containing:
local D = { }
global = setmetatable ({ }, {
 __newindex = function (t, n, v) rawset (_G, n, v) end,
 __index = rawget,
 })
global ._PROMPT = "> "
setmetatable (_G, {
 __newindex = function (t, n, v)
 if not D[n] then
 local w = debug.getinfo (2, "S").what
 if w ~= "C" then
 error ("\nattempt to write to undeclared variable " .. n, 2)
 end -- if
 D[n] = true
 end -- if
 rawset (t, n, v)
 end ,
 __index = function (_, n)
 if not D[n] then
 error ("\nattempt to read undeclared variable " .. n, 2)
 end -- if
 end,
} )
So the first assignment to a global variable x
has to be
 global.x = foo
but before that any reference to x raises an error.
--
Gavin Wraith (gavin@wra1th.plus.com)
Home page: http://www.wra1th.plus.com/

AltStyle によって変換されたページ (->オリジナル) /