Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gamestates3/data/lua/Strict.lua @ 10169

Last change on this file since 10169 was 6774, checked in by rgrieder, 15 years ago

Activated Strict.lua
That means you can no longer assign to or access an undeclared global variable on function scope.
Declaring: either assign anything to the variable (including nil) on file scope
or use the function global("myVar", "myVar2", …, "myVarN") (mind the strings!)

  • Property svn:eol-style set to native
File size: 1.1 KB
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 = true
16mt.__declared = {}
17
18mt.__newindex = function (t, n, v)
19  if not mt.__declared[n] then
20    if __STRICT then
21      local d = debug.getinfo(2, "S")
22      local w = d and d.what or "C"
23      if w ~= "main" and w ~= "C" then
24        error("Assigning to undeclared global variable '"..n.."'", 2)
25      end
26    end
27    mt.__declared[n] = true
28  end
29  rawset(t, n, v)
30end
31 
32mt.__index = function (t, n)
33  if not mt.__declared[n] then
34    local d = debug.getinfo(2, "S")
35    local w = d and d.what or "C"
36    if w ~= "C" then
37      error("Global variable '"..n.."' was not declared", 2)
38    else
39      mt.__declared[n] = true
40    end
41  end
42  return rawget(t, n)
43end
44
45function global(...)
46  for _, v in ipairs{...} do
47    mt.__declared[v] = true
48  end
49end
Note: See TracBrowser for help on using the repository browser.