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
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 core.log("warning", ("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 name ~= core.get_current_modname() then
34 core.log("warning", ("Global variable %q created at %s.")
37 rawset(self, name, value)
41 function meta:__index(name)
42 local info = debug.getinfo(2, "Sl")
43 local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
44 if not declared[name] and not warned[warn_key] and info.what ~= "C" then
45 core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
46 :format(name, info.short_src, info.currentline))
47 warned[warn_key] = true
49 return rawget(self, name)
52 setmetatable(_G, meta)