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 if type(name) ~= "string" then
9 error("core.global_exists: " .. tostring(name) .. " is not a string")
11 return rawget(_G, name) ~= nil
17 -- Key is source file, line, and variable name; seperated by NULs
20 function meta:__newindex(name, value)
21 local info = debug.getinfo(2, "Sl")
22 local desc = ("%s:%d"):format(info.short_src, info.currentline)
23 if not declared[name] then
24 local warn_key = ("%s\0%d\0%s"):format(info.source,
25 info.currentline, name)
26 if not warned[warn_key] and info.what ~= "main" and
28 core.log("warning", ("Assignment to undeclared "..
29 "global %q inside a function at %s.")
31 warned[warn_key] = true
35 -- Ignore mod namespaces
36 if WARN_INIT and name ~= core.get_current_modname() then
37 core.log("warning", ("Global variable %q created at %s.")
40 rawset(self, name, value)
44 function meta:__index(name)
45 local info = debug.getinfo(2, "Sl")
46 local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
47 if not declared[name] and not warned[warn_key] and info.what ~= "C" then
48 core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
49 :format(name, info.short_src, info.currentline))
50 warned[warn_key] = true
52 return rawget(self, name)
55 setmetatable(_G, meta)