]> git.lizzy.rs Git - minetest.git/blob - builtin/common/strict.lua
Fix console spaming by debug function on mod checking for global variable to exist.
[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 local function warn(message)
8         print(os.date("%H:%M:%S: WARNING: ")..message)
9 end
10
11
12 local meta = {}
13 local declared = {}
14 local alreadywarned = {}
15
16 function meta:__newindex(name, value)
17         local info = debug.getinfo(2, "Sl")
18         local desc = ("%s:%d"):format(info.short_src, info.currentline)
19         if not declared[name] then
20                 if info.what ~= "main" and info.what ~= "C" then
21                         warn(("Assignment to undeclared global %q inside"
22                                         .." a function at %s.")
23                                 :format(name, desc))
24                 end
25                 declared[name] = true
26         end
27         -- Ignore mod namespaces
28         if WARN_INIT and (not core.get_current_modname or
29                         name ~= core.get_current_modname()) then
30                 warn(("Global variable %q created at %s.")
31                         :format(name, desc))
32         end
33         rawset(self, name, value)
34 end
35
36
37 function meta:__index(name)
38         local info = debug.getinfo(2, "Sl")
39         if not declared[name] and info.what ~= "C" and not alreadywarned[name] then
40                 warn(("Undeclared global variable %q accessed at %s:%s")
41                                 :format(name, info.short_src, info.currentline))
42                 alreadywarned[name] = true
43         end
44         return rawget(self, name)
45 end
46
47 setmetatable(_G, meta)
48