]> git.lizzy.rs Git - metalua.git/blob - src/lib/strict.lua
Merge remote branch 'origin/master'
[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 getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
10
11 local mt = getmetatable(_G)
12 if mt == nil then
13   mt = {}
14   setmetatable(_G, mt)
15 end
16
17 __strict = true
18 mt.__declared = {}
19
20 local function what ()
21   local d = getinfo(3, "S")
22   return d and d.what or "C"
23 end
24
25 mt.__newindex = function (t, n, v)
26   if __strict and not mt.__declared[n] then
27     local w = what()
28     if w ~= "main" and w ~= "C" then
29       error("assign to undeclared variable '"..n.."'", 2)
30     end
31     mt.__declared[n] = true
32   end
33   rawset(t, n, v)
34 end
35   
36 mt.__index = function (t, n)
37   if __strict and not mt.__declared[n] and what() ~= "C" then
38     error("variable '"..n.."' is not declared", 2)
39   end
40   return rawget(t, n)
41 end
42
43 function global(...)
44    for _, v in ipairs{...} do mt.__declared[v] = true end
45 end