Skip to content

Instantly share code, notes, and snippets.

@appgurueu
Created Aug 22, 2021
Embed
What would you like to do?
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