Advertisement
crabb

swaa

Sep 19th, 2020 (edited)
968
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.06 KB | None | 0 0
  1. local swaa = {
  2.     case = function(sw,case,func)
  3.         sw.cases[case] = func; return sw
  4.     end,
  5.     case_list = function(sw,func,...)
  6.         for _,v in next,{...} do sw:case(v,func) end
  7.         return sw
  8.     end,
  9.     case_range = function(sw,caseA,caseB,func)
  10.         sw.range_cases[#sw.range_cases+1] = { caseA,caseB,func }
  11.         return sw
  12.     end,
  13.     close = function(sw)
  14.         if tonumber(sw.v) then
  15.             for _,v in next,sw.range_cases do
  16.                 if sw.v>=v[1] and sw.v<=v[2] then return v[3](sw.v) end
  17.             end
  18.         end
  19.         return (sw.cases[sw.v or "default"] or sw.cases["default"])(sw.v)
  20.     end
  21. }
  22. swaa.__index = swaa
  23.  
  24. local function swaa_new(v)
  25.     local cases = { default = function(v) end }
  26.     local range_cases = {}
  27.     return setmetatable({v=v,cases=cases,range_cases=range_cases,close=nil},swaa)
  28. end
  29.  
  30. local switch = swaa_new
  31.  
  32. print(
  33.     switch(0)
  34.         :case_range(0,7,function(v) print("between 0-7") return -1 end)
  35.         :case_list(function(v) print("between 11-12") return v-8 end,11,12)
  36.         :case(8,function(v) return 0 end)
  37.         :case(9,function(v) return 1 end)
  38.         :case(10,function(v) return 2 end)
  39.         :close()
  40. )
  41.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement