strict.lua 806 B

12345678910111213141516171819202122232425262728293031323334
  1. --
  2. -- strict.lua
  3. -- checks uses of undeclared global variables
  4. -- All global variables must be 'declared' through a regular assignment
  5. -- (even assigning nil will do) in a main chunk before being used
  6. -- anywhere or assigned to inside a function.
  7. --
  8. local mt = getmetatable(_G)
  9. if mt == nil then
  10. mt = {}
  11. setmetatable(_G, mt)
  12. end
  13. mt.__declared = {}
  14. mt.__newindex = function (t, n, v)
  15. if not mt.__declared[n] then
  16. local w = debug.getinfo(2, "S").what
  17. if w ~= "main" and w ~= "C" then
  18. error("assign to undeclared variable '"..n.."'", 2)
  19. end
  20. mt.__declared[n] = true
  21. end
  22. rawset(t, n, v)
  23. end
  24. mt.__index = function (t, n)
  25. if not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
  26. error("variable '"..n.."' is not declared", 2)
  27. end
  28. return rawget(t, n)
  29. end