Last active
December 14, 2015 09:38
-
-
Save westhood/5066011 to your computer and use it in GitHub Desktop.
Simulate go defer in lua
This file contains hidden or 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
| 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