Skip to content

Instantly share code, notes, and snippets.

@yaroslavche
Created January 12, 2020 14:37
Show Gist options
  • Save yaroslavche/7e2dfeb5cdf1e7bb1bd5623f0708d1e2 to your computer and use it in GitHub Desktop.
Save yaroslavche/7e2dfeb5cdf1e7bb1bd5623f0708d1e2 to your computer and use it in GitHub Desktop.
lua switch
local Switch = {
__tostring = function(self)
return string.format('%s (strict: %s)', tostring(self.expression), tostring(self.strict))
end
}
Switch.__index = Switch
function Switch:new(expression, strict)
if type(strict) ~= 'boolean' then strict = true end
local self = setmetatable({}, Switch)
self.expression = expression
self.strict = strict
self.matched = false
self.closed = false
self.case = function (case, callback)
if not self.closed and case == self.expression then
self.matched = true
if self.strict then self.closed = true end
callback()
end
end
self.default = function (callback)
if not self.closed and not self.matched then
if self.strict then self.closed = true end
callback()
end
end
return self
end
--------------------------------------------------
local check = 1;
local isOne = function ()
print('is one')
end
local isTwo = function ()
print('is two')
end
local default = function ()
print('default')
end
local switch = Switch:new(check, false);
print('switch expression: ' .. tostring(switch))
switch.case('1', isOne)
switch.case(1, isOne)
switch.case(2, isTwo)
switch.default(default)
switch.case(1, isOne)
switch.case(2, isTwo)
switch.default(default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment