Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --
- -- fascist.lua, like strict.lua but even more so.
- -- checks uses of uninitialized global variables
- -- All global variables must be not only declared but actually initialized
- -- in a main chunk by e.g. `global{a=1,b=2} before being used anywhere
- -- or assigned to inside a function.
- --
- -- Dirk Laurie, 2012
- --
- local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
- local mt = getmetatable(_G)
- if mt == nil then
- mt = {}
- setmetatable(_G, mt)
- end
- mt.__declared = {}
- local function what ()
- local d = getinfo(3, "S")
- return d and d.what or "C"
- end
- mt.__newindex = function (t, n, v)
- if not mt.__declared[n] and what() ~= "C" then
- error("assign to undeclared variable '"..n.."'", 2)
- end
- rawset(t, n, v)
- end
- mt.__index = function (t, n)
- if not mt.__declared[n] and what() ~= "C" then
- error("variable '"..n.."' is not declared", 2)
- end
- return rawget(t, n)
- end
- local function global(t)
- for k,v in pairs(t) do
- if mt.__declared[k] then error(
- "variable '"..n.."' is already declared", 2)
- end
- mt.__declared[k] = true; rawset(_G,k,v)
- end
- end
- local function liberate()
- mt.__index=nil; mt.__newindex=nil
- end
- rawset(_G,"global",global)
- rawset(_G,"liberate",liberate)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement