Skip to content

Instantly share code, notes, and snippets.

@CaptainPRICE
Last active September 30, 2016 17:08
Show Gist options
  • Select an option

  • Save CaptainPRICE/e9e316d31bc3a12966e6948746ceec31 to your computer and use it in GitHub Desktop.

Select an option

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
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
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