Skip to content

Instantly share code, notes, and snippets.

@picsoung
Created August 3, 2015 11:04
Show Gist options
  • Save picsoung/8e04fac92f883b3c9d77 to your computer and use it in GitHub Desktop.
Save picsoung/8e04fac92f883b3c9d77 to your computer and use it in GitHub Desktop.
a switch in Lua
-- fct to simulate a switch
function switch(t)
t.case = function (self,x)
local f=self[x] or self.default
if f then
if type(f)=="function" then
f(x,self)
else
error("case "..tostring(x).." not a function")
end
end
end
return t
end
@picsoung
Copy link
Author

picsoung commented Aug 3, 2015

usage

a = switch {
  [1] = function (x) print(x,10) end,
  [2] = function (x) print(x,20) end,
  default = function (x) print(x,0) end,
}

a:case(2)  -- ie. call case 2 
a:case(9)

found here: http://lua-users.org/wiki/SwitchStatement

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment