strict.lua 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. -- Always warn when creating a global variable, even outside of a function.
  2. -- This ignores mod namespaces (variables with the same name as the current mod).
  3. local WARN_INIT = false
  4. function core.global_exists(name)
  5. return rawget(_G, name) ~= nil
  6. end
  7. local meta = {}
  8. local declared = {}
  9. -- Key is source file, line, and variable name; seperated by NULs
  10. local warned = {}
  11. function meta:__newindex(name, value)
  12. local info = debug.getinfo(2, "Sl")
  13. local desc = ("%s:%d"):format(info.short_src, info.currentline)
  14. if not declared[name] then
  15. local warn_key = ("%s\0%d\0%s"):format(info.source,
  16. info.currentline, name)
  17. if not warned[warn_key] and info.what ~= "main" and
  18. info.what ~= "C" then
  19. core.log("warning", ("Assignment to undeclared "..
  20. "global %q inside a function at %s.")
  21. :format(name, desc))
  22. warned[warn_key] = true
  23. end
  24. declared[name] = true
  25. end
  26. -- Ignore mod namespaces
  27. if WARN_INIT and name ~= core.get_current_modname() then
  28. core.log("warning", ("Global variable %q created at %s.")
  29. :format(name, desc))
  30. end
  31. rawset(self, name, value)
  32. end
  33. function meta:__index(name)
  34. local info = debug.getinfo(2, "Sl")
  35. local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
  36. if not declared[name] and not warned[warn_key] and info.what ~= "C" then
  37. core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
  38. :format(name, info.short_src, info.currentline))
  39. warned[warn_key] = true
  40. end
  41. return rawget(self, name)
  42. end
  43. setmetatable(_G, meta)