Trying to lock a variable (and it's value) in _G, by making a new environment and resetting a changed _G variable back to default, if attempted to change it.
01 | -- CodingEvolution |
02 | -- Locking variables (and values) in _G |
03 |
04 | _G = { } -- New _G |
05 | _G.x = 1 |
06 | _G.y = 2 |
07 |
08 | setfenv ( 1 , setmetatable ( { } , { |
09 | __index = function (t,k) |
10 | if k = = '_G' then |
11 | return setmetatable ( { } , { |
12 | __newindex = function (t,k,v) |
13 | if k = = 'x' then |
14 | print 'This value is locked; changing back to default.' |
15 | rawset (t,k,_G [ k ] ) -- should set back to 1, but doesn't? |
Shouldn't rawset return the value of _G[k] from the previous environment? If not, why? Thank you for reading.
-- EDIT: You can run this code and test it here: http://repl.it/BCF6
I suppose you just have to set __index to _G, since the table is empty.
01 | _G = { } |
02 | _G.x = 1 |
03 | _G.y = 2 |
04 |
05 | setfenv ( 1 , setmetatable ( { } , { |
06 | __index = function (t,k) |
07 | if k = = '_G' then |
08 | return setmetatable ( { } , { |
09 | __newindex = function (t,k,v) |
10 | if k = = 'x' then |
11 | print 'This value is locked; changing back to default.' |
12 | rawset (t,k,_G [ k ] ) |
13 | else |
14 | print 'changing global...' |
15 | rawset (t,k,v) |