Last active
September 30, 2016 17:08
-
-
Save CaptainPRICE/e9e316d31bc3a12966e6948746ceec31 to your computer and use it in GitHub Desktop.
Simple implementation of "Switch-Case" and "Try-Catch" statements for Lua. For usage, see screenshot: https://i.imgur.com/SFC4wGj.png
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
| local setmetatable = setmetatable | |
| Default, Nil = {}, function() end | |
| switch = function(i) | |
| return setmetatable({ i }, { | |
| __call = function(t, cases) | |
| local item = #t < 1 and Nil or t[1] | |
| return (cases[item] or cases[Default] or Nil)(item) | |
| end | |
| }) | |
| end |
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
| local pcall = pcall | |
| local type = type | |
| catch = function(exception_handler) return exception_handler[1] end | |
| try = function(what) | |
| local status, result = pcall(what[1]) | |
| if status then return result end | |
| return type(what[2]) == "function" and what[2](result) or nil | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment