2 -- Always warn when creating a global variable, even outside of a function.
3 -- This ignores mod namespaces (variables with the same name as the current mod).
4 local WARN_INIT = false
7 local function warn(message)
8 print(os.date("%H:%M:%S: WARNING: ")..message)
14 local alreadywarned = {}
16 function meta:__newindex(name, value)
17 local info = debug.getinfo(2, "Sl")
18 local desc = ("%s:%d"):format(info.short_src, info.currentline)
19 if not declared[name] then
20 if info.what ~= "main" and info.what ~= "C" then
21 warn(("Assignment to undeclared global %q inside"
22 .." a function at %s.")
27 -- Ignore mod namespaces
28 if WARN_INIT and (not core.get_current_modname or
29 name ~= core.get_current_modname()) then
30 warn(("Global variable %q created at %s.")
33 rawset(self, name, value)
37 function meta:__index(name)
38 local info = debug.getinfo(2, "Sl")
39 if not declared[name] and info.what ~= "C" and not alreadywarned[name] then
40 warn(("Undeclared global variable %q accessed at %s:%s")
41 :format(name, info.short_src, info.currentline))
42 alreadywarned[name] = true
44 return rawget(self, name)
47 setmetatable(_G, meta)