0 Replies - 1109 Views - Last Post: 05 July 2010 - 05:07 PM

#1 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 117
  • View blog
  • Posts: 363
  • Joined: 20-August 08

[LUA]Prevent Creation of Global Variables

Posted 05 July 2010 - 05:07 PM

Description: Tested on Lua 5.1.3Uses meta-methods to allow you to explicitly disable the creation of any new global variables. To make it convenient, it includes two functions, one to lock, and one to unlock. Enjoy :)
-- This function prevents the creation of any new global 
-- vars. It works by using meta-methods to save the current
-- state, and disallow new reads and writes.
function lockglobalenvironment()
    local function _n(t, i, k) 
        error("writing to new global variables is disabled.", 2);
    end

    local function _i(t, i)
        error("reading to new global variables is disabled.", 2);
    end

    -- work with the global variable table ('_G')
    local mt = { __newindex = _n, __index = _i };
    setmetatable(_G, mt);
end

-- this reverts the global variable lock.
function unlockglobalenvironment()
    local mt = getmetatable(_G);
    mt.__index = nil;
    mt.__newindex = nil;
end




-- Example usgae...

-- Make some new globals. OK.
x,k,z = 3,5,7;

-- Lock environment.
lockglobalenvironment();  

-- working with existing variables is legal...
x = 45;

-- but either of the following would cause an error:
-- f = 6765465.8; <- f isn't declared
-- x = h; <- h isn't declared

-- undo the damage ;)
unlockglobalenvironment();

-- now these two statements are legal...
f = 6765465.8;
x = h;


Is This A Good Question/Topic? 0
  • +

Page 1 of 1