Last change
on this file since 6858 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 | |
---|
9 | local mt = getmetatable(_G) |
---|
10 | if mt == nil then |
---|
11 | mt = {} |
---|
12 | setmetatable(_G, mt) |
---|
13 | end |
---|
14 | |
---|
15 | __STRICT = false |
---|
16 | mt.__declared = {} |
---|
17 | |
---|
18 | mt.__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) |
---|
28 | end |
---|
29 | |
---|
30 | mt.__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) |
---|
35 | end |
---|
36 | |
---|
37 | function global(...) |
---|
38 | for _, v in ipairs{...} do mt.__declared[v] = true end |
---|
39 | end |
---|
Note: See
TracBrowser
for help on using the repository browser.