]> git.lizzy.rs Git - minetest.git/blob - builtin/common/strict.lua
Refactor logging
[minetest.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         return rawget(_G, name) ~= nil
9 end
10
11
12 local meta = {}
13 local declared = {}
14 -- Key is source file, line, and variable name; seperated by NULs
15 local warned = {}
16
17 function meta:__newindex(name, value)
18         local info = debug.getinfo(2, "Sl")
19         local desc = ("%s:%d"):format(info.short_src, info.currentline)
20         if not declared[name] then
21                 local warn_key = ("%s\0%d\0%s"):format(info.source,
22                                 info.currentline, name)
23                 if not warned[warn_key] and info.what ~= "main" and
24                                 info.what ~= "C" then
25                         core.log("warning", ("Assignment to undeclared "..
26                                         "global %q inside a function at %s.")
27                                 :format(name, desc))
28                         warned[warn_key] = true
29                 end
30                 declared[name] = true
31         end
32         -- Ignore mod namespaces
33         if WARN_INIT and name ~= core.get_current_modname() then
34                 core.log("warning", ("Global variable %q created at %s.")
35                         :format(name, desc))
36         end
37         rawset(self, name, value)
38 end
39
40
41 function meta:__index(name)
42         local info = debug.getinfo(2, "Sl")
43         local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
44         if not declared[name] and not warned[warn_key] and info.what ~= "C" then
45                 core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
46                                 :format(name, info.short_src, info.currentline))
47                 warned[warn_key] = true
48         end
49         return rawget(self, name)
50 end
51
52 setmetatable(_G, meta)
53