2022-07-02 20:58:15 +02:00
|
|
|
local getinfo, rawget, rawset = debug.getinfo, rawget, rawset
|
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 = {}
|
2022-11-09 17:57:19 +01:00
|
|
|
-- Key is source file, line, and variable name; separated by NULs
|
2014-11-23 22:30:14 +01:00
|
|
|
local warned = {}
|
2014-06-05 18:40:34 +02:00
|
|
|
|
|
|
|
function meta:__newindex(name, value)
|
2023-01-09 21:00:49 +01:00
|
|
|
rawset(self, name, value)
|
2022-07-02 20:58:15 +02:00
|
|
|
if declared[name] then
|
|
|
|
return
|
|
|
|
end
|
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)
|
2022-07-02 20:58:15 +02: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
|
|
|
|
core.log("warning", ("Assignment to undeclared global %q inside a function at %s.")
|
2014-06-05 18:40:34 +02:00
|
|
|
:format(name, desc))
|
2022-07-02 20:58:15 +02:00
|
|
|
warned[warn_key] = true
|
2014-06-05 18:40:34 +02:00
|
|
|
end
|
2022-07-02 20:58:15 +02:00
|
|
|
declared[name] = true
|
2014-06-05 18:40:34 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
function meta:__index(name)
|
2022-07-02 20:58:15 +02:00
|
|
|
if declared[name] then
|
|
|
|
return
|
|
|
|
end
|
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)
|
2022-07-02 20:58:15 +02:00
|
|
|
if 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
|
|
|
|
end
|
|
|
|
|
|
|
|
setmetatable(_G, meta)
|