Skip to content

Instantly share code, notes, and snippets.

@toriaezunama
Last active January 1, 2016 06:49
Show Gist options
  • Save toriaezunama/8107755 to your computer and use it in GitHub Desktop.
Save toriaezunama/8107755 to your computer and use it in GitHub Desktop.
Simple module definition that prevents overwriting globals by accident *N.B. This won't work on Lua >= 5.2 because of the new _ENV*
local M = {
__index = _G,
__newindex = function( t, k, v )
if rawget( _G, k ) ~= nil then
print( string.format( "Setting key '%s', on table %s masks a value in _G!!", tostring( k ), tostring( t ) ) )
error()
else
rawset( t, k, v )
end
end
}
setmetatable( M, M ) -- re-use table. Saves having an extra table just to hold __index and __newindex
setfenv( 1, M )
-- table = 5 -- 1) un-comment to cause an error
-- M.table = 5 -- 2) M.table == table == _G.table
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment