Created
August 22, 2021 10:32
-
-
Save appgurueu/3d03d5a1537e60ed804cfe15cae29122 to your computer and use it in GitHub Desktop.
JS var keyword
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 _G = _G | |
return function(implicit_declaration, stacklevel) | |
assert(implicit_declaration == "var" or implicit_declaration == "global" or not implicit_declaration) | |
stacklevel = (stacklevel or 1) + 1 | |
local _P = getfenv(stacklevel + 1) | |
local _V = {} | |
local declarations = {} | |
local environment = { | |
_P = _P, | |
_V = _V, | |
var = function(name) | |
declarations[name] = "var" | |
end, | |
global = function(name) | |
declarations[name] = "global" | |
end | |
} | |
setmetatable(environment, { | |
__index = function(_, name) | |
local declaration = declarations[name] | |
if declaration == "var" then | |
return _V[name] | |
end | |
if declaration == "global" then | |
return _G[name] | |
end | |
-- vars of outer functions are accessed just fine throug this | |
return _P[name] | |
end, | |
__newindex = function(self, name, value) | |
local declaration = declarations[name] | |
if declaration == "var" then | |
_V[name] = value | |
return | |
end | |
if declaration == "global" then | |
_G[name] = value | |
return | |
end | |
if implicit_declaration then | |
declarations[name] = implicit_declaration | |
-- recursive call | |
self[name] = value | |
return | |
end | |
-- Set in parent environment | |
-- TODO check for declaration, perhaps recursively? | |
_P[name] = value | |
end | |
}) | |
-- Set the environment of the calling function | |
setfenv(stacklevel, environment) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment