]> git.lizzy.rs Git - minetest.git/blob - builtin/common/strict.lua
Change assignment to global in a function to warning
[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 -- 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                         warn(("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 (not core.get_current_modname or
34                         name ~= core.get_current_modname()) then
35                 warn(("Global variable %q created at %s.")
36                         :format(name, desc))
37         end
38         rawset(self, name, value)
39 end
40
41
42 function meta:__index(name)
43         local info = debug.getinfo(2, "Sl")
44         local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
45         if not declared[name] and not warned[warn_key] and info.what ~= "C" then
46                 warn(("Undeclared global variable %q accessed at %s:%s")
47                                 :format(name, info.short_src, info.currentline))
48                 warned[warn_key] = true
49         end
50         return rawget(self, name)
51 end
52
53 setmetatable(_G, meta)
54