2017-01-28 17:24:25 +01:00
|
|
|
local getinfo = debug.getinfo
|
2014-06-05 18:40:34 +02:00
|
|
|
|
2014-11-21 17:32:01 +01:00
|
|
|
function core.global_exists(name)
|
2016-06-28 06:34:22 +02:00
|
|
|
if type(name) ~= "string" then
|
|
|
|
error("core.global_exists: " .. tostring(name) .. " is not a string")
|
|
|
|
end
|
2014-11-21 17:32:01 +01:00
|
|
|
return rawget(_G, name) ~= nil
|
|
|
|
end
|
|
|
|
|
|
|
|
|
2014-06-05 18:40:34 +02:00
|
|
|
local meta = {}
|
|
|
|
local declared = {}
|
2014-11-23 22:30:14 +01:00
|
|
|
-- Key is source file, line, and variable name; seperated by NULs
|
|
|
|
local warned = {}
|
2014-06-05 18:40:34 +02:00
|
|
|
|
|
|
|
function meta:__newindex(name, value)
|
2017-01-28 17:24:25 +01:00
|
|
|
local info = getinfo(2, "Sl")
|
2014-06-05 18:40:34 +02:00
|
|
|
local desc = ("%s:%d"):format(info.short_src, info.currentline)
|
|
|
|
if not declared[name] then
|
2014-11-23 22:30:14 +01: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 09:57:44 +02:00
|
|
|
core.log("warning", ("Assignment to undeclared "..
|
2014-11-23 22:30:14 +01:00
|
|
|
"global %q inside a function at %s.")
|
2014-06-05 18:40:34 +02:00
|
|
|
:format(name, desc))
|
2014-11-23 22:30:14 +01:00
|
|
|
warned[warn_key] = true
|
2014-06-05 18:40:34 +02:00
|
|
|
end
|
|
|
|
declared[name] = true
|
|
|
|
end
|
|
|
|
rawset(self, name, value)
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
function meta:__index(name)
|
2017-01-28 17:24:25 +01:00
|
|
|
local info = getinfo(2, "Sl")
|
2014-11-23 22:30:14 +01: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 09:57:44 +02:00
|
|
|
core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
|
2014-06-05 18:40:34 +02:00
|
|
|
:format(name, info.short_src, info.currentline))
|
2014-11-23 22:30:14 +01:00
|
|
|
warned[warn_key] = true
|
2014-06-05 18:40:34 +02:00
|
|
|
end
|
|
|
|
return rawget(self, name)
|
|
|
|
end
|
|
|
|
|
|
|
|
setmetatable(_G, meta)
|