Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Help with setmetatable and _G?

Asked by 9 years ago

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 
08setfenv(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?
View all 34 lines...

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

1 answer

Log in to vote
1
Answered by
funyun 958 Moderation Voter
9 years ago

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 
05setfenv(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)
View all 31 lines...
1
Thank you very much sir. CodingEvolution 490 — 9y
Ad

Answer this question