File: strict.lua

package info (click to toggle)
lua-penlight 1.0.2%2Bhtmldoc-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,860 kB
  • sloc: makefile: 7
file content (70 lines) | stat: -rw-r--r-- 1,573 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
--- 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.
-- @module pl.strict

require 'debug'
local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
local handler,hooked

local mt = getmetatable(_G)
if mt == nil then
  mt = {}
  setmetatable(_G, mt)
elseif mt.hook then
    hooked = true
end

-- predeclaring _PROMPT keeps the Lua Interpreter happy
mt.__declared = {_PROMPT=true}

local function what ()
  local d = getinfo(3, "S")
  return d and d.what or "C"
end

mt.__newindex = function (t, n, v)
  if not mt.__declared[n] then
    local w = what()
    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

handler = function(t,n)
  if not mt.__declared[n] and what() ~= "C" then
    error("variable '"..n.."' is not declared", 2)
  end
  return rawget(t, n)
end

function package.strict (mod)
    local mt = getmetatable(mod)
    if mt == nil then
      mt = {}
      setmetatable(mod, mt)
    end
    mt.__declared = {}
    mt.__newindex = function(t, n, v)
        mt.__declared[n] = true
        rawset(t, n, v)
    end
    mt.__index = function(t,n)
      if not mt.__declared[n] then
        error("variable '"..n.."' is not declared", 2)
      end
      return rawget(t, n)
    end
end

if not hooked then
    mt.__index = handler
else
    mt.hook(handler)
end