Skip to content

Latest commit

 

History

History
41 lines (34 loc) · 928 Bytes

strict.lua

File metadata and controls

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