Skip to content

Instantly share code, notes, and snippets.

@westhood
Last active December 14, 2015 09:38
Show Gist options
  • Select an option

  • Save westhood/5066011 to your computer and use it in GitHub Desktop.

Select an option

Save westhood/5066011 to your computer and use it in GitHub Desktop.
Simulate go defer in lua
function scoped(...)
local args = {...}
local alias, f
if #args == 1 then
f = args[1]
alias = "defer"
elseif # args == 2 then
f = args[2]
alias = args[1]
else
error("scoped takes 1 or 2 arguments")
end
assert(type(alias) == "string", "type of the alias should be string")
local stack = {}
local env = {}
env[alias] = function(cb, ...)
stack[#stack + 1] = {cb, { ... }}
end
setmetatable(env, {__index = _G, __newindex = _G})
setfenv(f, env)
local rets = {pcall(f)}
for i = #stack, 1, -1 do
local cb, args = unpack(stack[i])
cb(unpack(args))
end
if rets[1] == true then
return unpack(rets, 2)
else
error(rets[2])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment