Skip to content

Instantly share code, notes, and snippets.

@outro56
Created June 30, 2015 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save outro56/82c3c4f9e57e7f548831 to your computer and use it in GitHub Desktop.
Save outro56/82c3c4f9e57e7f548831 to your computer and use it in GitHub Desktop.
Detecting undefined variables in Lua (http://lua-users.org/wiki/DetectingUndefinedVariables)
--===================================================
--= Niklas Frykholm
-- basically if user tries to create global variable
-- the system will not let them!!
-- call GLOBAL_lock(_G)
--
--===================================================
function GLOBAL_lock(t)
local mt = getmetatable(t) or {}
mt.__newindex = lock_new_index
setmetatable(t, mt)
end
--===================================================
-- call GLOBAL_unlock(_G)
-- to change things back to normal.
--===================================================
function GLOBAL_unlock(t)
local mt = getmetatable(t) or {}
mt.__newindex = unlock_new_index
setmetatable(t, mt)
end
function lock_new_index(t, k, v)
if (k~="_" and string.sub(k,1,2) ~= "__") then
GLOBAL_unlock(_G)
error("GLOBALS are locked -- " .. k ..
" must be declared local or prefix with '__' for globals.", 2)
else
rawset(t, k, v)
end
end
function unlock_new_index(t, k, v)
rawset(t, k, v)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment