Module:No globals

Revision as of 20:38, 23 April 2014 by Jackmcbarn (talk | contribs) (Created page with 'local mt = getmetatable(_G) or {} local oldIndex = mt.__index or function() return nil end mt.__index = function(t, k) if k ~= 'name' and k ~= 'arg' then erro...')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

This module causes an error if any nil global is read or if any global is written to, with the exception of arg. To use, add require('Module:No globals') to the top of the module using it. The arg variable is excluded because it is necessary for Scribunto's require function to work properly. (See the Scribunto source code here.)

Code

local mt = getmetatable(_G) or {}
local oldIndex = mt.__index or function() return nil end
mt.__index = function(t, k)
	if k ~= 'name' and k ~= 'arg' then
		error('Tried to read nil global ' .. tostring(k), 2)
	end
	return oldIndex(t, k)
end
local oldNewindex = mt.__newindex or rawset
function mt.__newindex(t, k, v)
	if k ~= 'name' and k ~= 'arg' then
		error('Tried to write global ' .. tostring(k), 2)
	end
	oldNewindex(t, k, v)
end
setmetatable(_G, mt)