Created
January 6, 2019 20:31
-
-
Save ochaton/06b8850538543e066f178adaf5b27f50 to your computer and use it in GitHub Desktop.
dynamic scoping in Lua
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
-- Code was taken from http://leafo.net/guides/dynamic-scoping-in-lua.html | |
function dynamic(name) | |
local level = 2 | |
-- iterate over | |
while true do | |
if not debug.getinfo(level) then | |
-- check that we didn't leave the call-stack | |
break | |
end | |
local i = 1 | |
-- iterate over each local by index | |
local found, found_val | |
while true do | |
local local_name, local_val = debug.getlocal(level, i) | |
if not local_name then break end | |
if local_name == name then | |
-- save last found value of variable in `found_val` | |
found = true | |
found_val = local_val | |
end | |
i = i + 1 | |
end | |
if found then | |
return found_val | |
end | |
level = level + 1 | |
end | |
end | |
local function generator (...) | |
local a = 100 | |
return function () | |
print("Lexical: ", a) | |
print("Dynamic: ", dynamic("a")) | |
end | |
end | |
local function runner(call, a) | |
local a = 200 | |
call(a) | |
end | |
print(_VERSION) | |
runner(generator(), 400) | |
--[[ | |
Lua 5.1 | |
Lexical: 100 | |
Dynamic: 200 | |
]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment