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 function core.global_exists(name)
8 return rawget(_G, name) ~= nil
12 local function warn(message)
13 print(os.date("%H:%M:%S: WARNING: ")..message)
19 -- Key is source file, line, and variable name; seperated by NULs
22 function meta:__newindex(name, value)
23 local info = debug.getinfo(2, "Sl")
24 local desc = ("%s:%d"):format(info.short_src, info.currentline)
25 if not declared[name] then
26 local warn_key = ("%s\0%d\0%s"):format(info.source,
27 info.currentline, name)
28 if not warned[warn_key] and info.what ~= "main" and
30 warn(("Assignment to undeclared "..
31 "global %q inside a function at %s.")
33 warned[warn_key] = true
37 -- Ignore mod namespaces
38 if WARN_INIT and (not core.get_current_modname or
39 name ~= core.get_current_modname()) then
40 warn(("Global variable %q created at %s.")
43 rawset(self, name, value)
47 function meta:__index(name)
48 local info = debug.getinfo(2, "Sl")
49 local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
50 if not declared[name] and not warned[warn_key] and info.what ~= "C" then
51 warn(("Undeclared global variable %q accessed at %s:%s")
52 :format(name, info.short_src, info.currentline))
53 warned[warn_key] = true
55 return rawget(self, name)
58 setmetatable(_G, meta)