2014-06-05 12:40:34 -04:00
|
|
|
|
|
|
|
-- Always warn when creating a global variable, even outside of a function.
|
|
|
|
-- This ignores mod namespaces (variables with the same name as the current mod).
|
|
|
|
local WARN_INIT = false
|
|
|
|
|
|
|
|
|
2014-11-21 11:32:01 -05:00
|
|
|
function core.global_exists(name)
|
2016-06-28 00:34:22 -04:00
|
|
|
if type(name) ~= "string" then
|
|
|
|
error("core.global_exists: " .. tostring(name) .. " is not a string")
|
|
|
|
end
|
2014-11-21 11:32:01 -05:00
|
|
|
return rawget(_G, name) ~= nil
|
|
|
|
end
|
|
|
|
|
|
|
|
|
2014-06-05 12:40:34 -04:00
|
|
|
local meta = {}
|
|
|
|
local declared = {}
|
2014-11-23 16:30:14 -05:00
|
|
|
-- Key is source file, line, and variable name; seperated by NULs
|
|
|
|
local warned = {}
|
2014-06-05 12:40:34 -04:00
|
|
|
|
|
|
|
function meta:__newindex(name, value)
|
|
|
|
local info = debug.getinfo(2, "Sl")
|
|
|
|
local desc = ("%s:%d"):format(info.short_src, info.currentline)
|
|
|
|
if not declared[name] then
|
2014-11-23 16:30:14 -05:00
|
|
|
local warn_key = ("%s\0%d\0%s"):format(info.source,
|
|
|
|
info.currentline, name)
|
|
|
|
if not warned[warn_key] and info.what ~= "main" and
|
|
|
|
info.what ~= "C" then
|
2015-10-13 03:57:44 -04:00
|
|
|
core.log("warning", ("Assignment to undeclared "..
|
2014-11-23 16:30:14 -05:00
|
|
|
"global %q inside a function at %s.")
|
2014-06-05 12:40:34 -04:00
|
|
|
:format(name, desc))
|
2014-11-23 16:30:14 -05:00
|
|
|
warned[warn_key] = true
|
2014-06-05 12:40:34 -04:00
|
|
|
end
|
|
|
|
declared[name] = true
|
|
|
|
end
|
|
|
|
-- Ignore mod namespaces
|
2015-10-13 03:57:44 -04:00
|
|
|
if WARN_INIT and name ~= core.get_current_modname() then
|
|
|
|
core.log("warning", ("Global variable %q created at %s.")
|
2014-06-05 12:40:34 -04:00
|
|
|
:format(name, desc))
|
|
|
|
end
|
|
|
|
rawset(self, name, value)
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
function meta:__index(name)
|
|
|
|
local info = debug.getinfo(2, "Sl")
|
2014-11-23 16:30:14 -05:00
|
|
|
local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
|
|
|
|
if not declared[name] and not warned[warn_key] and info.what ~= "C" then
|
2015-10-13 03:57:44 -04:00
|
|
|
core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
|
2014-06-05 12:40:34 -04:00
|
|
|
:format(name, info.short_src, info.currentline))
|
2014-11-23 16:30:14 -05:00
|
|
|
warned[warn_key] = true
|
2014-06-05 12:40:34 -04:00
|
|
|
end
|
|
|
|
return rawget(self, name)
|
|
|
|
end
|
|
|
|
|
|
|
|
setmetatable(_G, meta)
|
|
|
|
|