]> git.lizzy.rs Git - metalua.git/blob - src/lib/strict.lua
8ca18fab3f11536010344977037c58d365963cae
[metalua.git] / src / lib / strict.lua
1 --
2 -- strict.lua
3 -- checks uses of undeclared global variables
4 -- All global variables must be 'declared' through a regular assignment
5 -- (even assigning nil will do) in a main chunk before being used
6 -- anywhere or assigned to inside a function.
7 --
8
9 local mt = getmetatable(_G)
10 if mt == nil then
11   mt = {}
12   setmetatable(_G, mt)
13 end
14
15 __STRICT = true
16 mt.__declared = {}
17
18 mt.__newindex = function (t, n, v)
19   if __STRICT and not mt.__declared[n] then
20     local w = debug.getinfo(2, "S").what
21     if w ~= "main" and w ~= "C" then
22       error("assign to undeclared variable '"..n.."'", 2)
23     end
24     mt.__declared[n] = true
25   end
26   rawset(t, n, v)
27 end
28   
29 mt.__index = function (t, n)
30   if not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
31     error("variable '"..n.."' is not declared", 2)
32   end
33   return rawget(t, n)
34 end
35
36 function global(...)
37    for _, v in ipairs{...} do mt.__declared[v] = true end
38 end