/game/scripts/nil.lua

https://bitbucket.org/vivkin/gam3b00bs/ · Lua · 42 lines · 24 code · 11 blank · 7 comment · 2 complexity · 9a56e37cacfd5b237c377e65bdfd482e MD5 · raw file

  1. --
  2. -- nil.lua: restricts global var writes and catches undefined global var access
  3. --
  4. --
  5. print "nil.lua"
  6. do
  7. local mt = {};
  8. mt.__index = function( t, k ) error("Attempt to access global '" .. k .. "' (nil)") end;
  9. mt.__newindex = function( t, k, v ) error("Attempt to write global '" .. k .. "'" ) end;
  10. setmetatable( _G, mt );
  11. rawset( _G, "global", function(expr)
  12. for k,v in pairs(expr) do
  13. rawset( _G, k, v );
  14. end;
  15. end );
  16. end
  17. -- Tests:
  18. if 1 then
  19. -- should raise an error
  20. local function test_for_global_access()
  21. XXXXXXXXXXX = 42
  22. end
  23. --- should raise an error
  24. local function test_for_uninitialized_global()
  25. local var = XXXXXXXXXXXXXXXXXX
  26. end
  27. local result,message = pcall( test_for_global_access )
  28. assert( not result, "Test test_for_global_access FAILED!" )
  29. local result,message = pcall( test_for_uninitialized_global )
  30. assert( not result, "Test test_for_uninitialized_global failed!" )
  31. end