Advertisement
robn

Untitled

Jun 4th, 2012
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.28 KB | None | 0 0
  1. --
  2. -- fascist.lua, like strict.lua but even more so.
  3. -- checks uses of uninitialized global variables
  4. -- All global variables must be not only declared but actually initialized
  5. -- in a main chunk by e.g. `global{a=1,b=2} before being used anywhere
  6. -- or assigned to inside a function.  
  7. --
  8. -- Dirk Laurie, 2012
  9. --
  10.  
  11. local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
  12.  
  13. local mt = getmetatable(_G)
  14. if mt == nil then
  15.   mt = {}
  16.   setmetatable(_G, mt)
  17. end
  18.  
  19. mt.__declared = {}
  20.  
  21. local function what ()
  22.   local d = getinfo(3, "S")
  23.   return d and d.what or "C"
  24. end
  25.  
  26. mt.__newindex = function (t, n, v)
  27.   if not mt.__declared[n] and what() ~= "C" then
  28.       error("assign to undeclared variable '"..n.."'", 2)
  29.     end
  30.   rawset(t, n, v)
  31. end
  32.  
  33. mt.__index = function (t, n)
  34.   if not mt.__declared[n] and what() ~= "C" then
  35.     error("variable '"..n.."' is not declared", 2)
  36.   end
  37.   return rawget(t, n)
  38. end
  39.  
  40. local function global(t)
  41.    for k,v in pairs(t) do
  42.       if mt.__declared[k] then error(
  43.          "variable '"..n.."' is already declared", 2)
  44.       end
  45.       mt.__declared[k] = true; rawset(_G,k,v)
  46.    end
  47. end
  48.  
  49. local function liberate()
  50.    mt.__index=nil; mt.__newindex=nil
  51. end
  52.  
  53. rawset(_G,"global",global)
  54. rawset(_G,"liberate",liberate)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement