Skip to content

Instantly share code, notes, and snippets.

@appgurueu
Created August 22, 2021 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appgurueu/3d03d5a1537e60ed804cfe15cae29122 to your computer and use it in GitHub Desktop.
Save appgurueu/3d03d5a1537e60ed804cfe15cae29122 to your computer and use it in GitHub Desktop.
JS var keyword
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