[Orxonox-commit 1913] r6630 - code/branches/gamestate/data/lua
rgrieder at orxonox.net
rgrieder at orxonox.net
Sun Mar 28 22:47:27 CEST 2010
Author: rgrieder
Date: 2010-03-28 22:47:27 +0200 (Sun, 28 Mar 2010)
New Revision: 6630
Added:
code/branches/gamestate/data/lua/Strict.lua
Log:
Added Strict.lua: When activated with require("Strict"), it will check for not initialised global variables.
Currently, our scripts REALLY don't like that..
Added: code/branches/gamestate/data/lua/Strict.lua
===================================================================
--- code/branches/gamestate/data/lua/Strict.lua (rev 0)
+++ code/branches/gamestate/data/lua/Strict.lua 2010-03-28 20:47:27 UTC (rev 6630)
@@ -0,0 +1,39 @@
+--
+-- strict.lua
+-- 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.
+--
+
+local mt = getmetatable(_G)
+if mt == nil then
+ mt = {}
+ setmetatable(_G, mt)
+end
+
+__STRICT = false
+mt.__declared = {}
+
+mt.__newindex = function (t, n, v)
+ if __STRICT and not mt.__declared[n] then
+ local d = debug.getinfo(2, "S")
+ local w = d and d.what or "C"
+ 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
+
+mt.__index = function (t, n)
+ if not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
+ error("variable '"..n.."' is not declared", 2)
+ end
+ return rawget(t, n)
+end
+
+function global(...)
+ for _, v in ipairs{...} do mt.__declared[v] = true end
+end
More information about the Orxonox-commit
mailing list