Last active
January 1, 2016 06:49
-
-
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*
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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