Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gamestate/data/lua/Strict.lua @ 7221

Last change on this file since 7221 was 6630, checked in by rgrieder, 15 years ago

Added Strict.lua: When activated with require("Strict"), it will check for not initialised global variables.
Currently, our scripts REALLY don't like that..

File size: 987 bytes
Line 
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
9local mt = getmetatable(_G)
10if mt == nil then
11  mt = {}
12  setmetatable(_G, mt)
13end
14
15__STRICT = false
16mt.__declared = {}
17
18mt.__newindex = function (t, n, v)
19  if __STRICT and not mt.__declared[n] then
20    local d = debug.getinfo(2, "S")
21    local w = d and d.what or "C"
22    if w ~= "main" and w ~= "C" then
23      error("assign to undeclared variable '"..n.."'", 2)
24    end
25    mt.__declared[n] = true
26  end
27  rawset(t, n, v)
28end
29 
30mt.__index = function (t, n)
31  if not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
32    error("variable '"..n.."' is not declared", 2)
33  end
34  return rawget(t, n)
35end
36
37function global(...)
38   for _, v in ipairs{...} do mt.__declared[v] = true end
39end
Note: See TracBrowser for help on using the repository browser.