]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/common/strict.lua
Add search to advanced settings (#4806)
[dragonfireclient.git] / builtin / common / strict.lua
1
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
5
6
7 function core.global_exists(name)
8         if type(name) ~= "string" then
9                 error("core.global_exists: " .. tostring(name) .. " is not a string")
10         end
11         return rawget(_G, name) ~= nil
12 end
13
14
15 local meta = {}
16 local declared = {}
17 -- Key is source file, line, and variable name; seperated by NULs
18 local warned = {}
19
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
27                                 info.what ~= "C" then
28                         core.log("warning", ("Assignment to undeclared "..
29                                         "global %q inside a function at %s.")
30                                 :format(name, desc))
31                         warned[warn_key] = true
32                 end
33                 declared[name] = true
34         end
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.")
38                         :format(name, desc))
39         end
40         rawset(self, name, value)
41 end
42
43
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
51         end
52         return rawget(self, name)
53 end
54
55 setmetatable(_G, meta)
56