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