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