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 -- Key is source file, line, and variable name; seperated by NULs
17 function meta:__newindex(name, value)
18 local info = debug.getinfo(2, "Sl")
19 local desc = ("%s:%d"):format(info.short_src, info.currentline)
20 if not declared[name] then
21 local warn_key = ("%s\0%d\0%s"):format(info.source,
22 info.currentline, name)
23 if not warned[warn_key] and info.what ~= "main" and
25 warn(("Assignment to undeclared "..
26 "global %q inside a function at %s.")
28 warned[warn_key] = true
32 -- Ignore mod namespaces
33 if WARN_INIT and (not core.get_current_modname or
34 name ~= core.get_current_modname()) then
35 warn(("Global variable %q created at %s.")
38 rawset(self, name, value)
42 function meta:__index(name)
43 local info = debug.getinfo(2, "Sl")
44 local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
45 if not declared[name] and not warned[warn_key] and info.what ~= "C" then
46 warn(("Undeclared global variable %q accessed at %s:%s")
47 :format(name, info.short_src, info.currentline))
48 warned[warn_key] = true
50 return rawget(self, name)
53 setmetatable(_G, meta)