Updated lua to version 5.1.2.
[tagua.git] / lua / etc / strict.lua
blob16ee26b429efa7fd0a9ed29d524e3486b681312e
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 --
9 local mt = getmetatable(_G)
10 if mt == nil then
11 mt = {}
12 setmetatable(_G, mt)
13 end
15 mt.__declared = {}
17 local function what ()
18 local d = debug.getinfo(3, "S")
19 return d and d.what or "C"
20 end
22 mt.__newindex = function (t, n, v)
23 if not mt.__declared[n] then
24 local w = what()
25 if w ~= "main" and w ~= "C" then
26 error("assign to undeclared variable '"..n.."'", 2)
27 end
28 mt.__declared[n] = true
29 end
30 rawset(t, n, v)
31 end
33 mt.__index = function (t, n)
34 if not mt.__declared[n] and what() ~= "C" then
35 error("variable '"..n.."' is not declared", 2)
36 end
37 return rawget(t, n)
38 end