Skip to content

Instantly share code, notes, and snippets.

@ochaton
Created January 6, 2019 20:31
Show Gist options
  • Save ochaton/06b8850538543e066f178adaf5b27f50 to your computer and use it in GitHub Desktop.
Save ochaton/06b8850538543e066f178adaf5b27f50 to your computer and use it in GitHub Desktop.
dynamic scoping in Lua
-- 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