Files

42 lines
928 B
Lua
Raw Permalink Normal View History

2011-03-17 01:47:30 -04:00
--
-- 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.
--
2022-01-23 10:38:48 +01:00
local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
2011-03-17 01:47:30 -04:00
local mt = getmetatable(_G)
if mt == nil then
mt = {}
setmetatable(_G, mt)
end
mt.__declared = {}
2022-01-23 10:38:48 +01:00
local function what ()
local d = getinfo(3, "S")
return d and d.what or "C"
end
2011-03-17 01:47:30 -04:00
mt.__newindex = function (t, n, v)
if not mt.__declared[n] then
2022-01-23 10:38:48 +01:00
local w = what()
2011-03-17 01:47:30 -04:00
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)
2022-01-23 10:38:48 +01:00
if not mt.__declared[n] and what() ~= "C" then
2011-03-17 01:47:30 -04:00
error("variable '"..n.."' is not declared", 2)
end
return rawget(t, n)
end