Module:no globals

Definition from Wiktionary, the free dictionary
Jump to navigation Jump to search

This module, when it is used in another module, sends a module error whenever a global variable is written or read. Global variables are discouraged (see WT:LUA). It should not be used in modules that are invoked in entries, because it will bleed across to other modules, some of which have global variables, causing module errors. It can be used as a tool while previewing pages with the module.

To use it, type require("Module:no globals"). The module does not return a value, so you do not have to assign a variable to it.


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