Advertisement
Filtered_Dev

Switch Module

Jul 8th, 2020
1,722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.44 KB | None | 0 0
  1. --[[Switch-Case Simulation in Lua
  2.  
  3. DOCUMENTATION
  4.  
  5. SWITCH MODULE
  6.  
  7.     local Switch = require(script.Switch) --returns a callable function for constructing Switch objects
  8.  
  9. Switch Object
  10.  
  11.     __call(variable) - Checks a specified variable amongst case statements. Uses :default if no value is found. If :default is not declared, this will error
  12.  
  13.     self :case(value, callback) - Sets a case value to callback, returns the object so that it can be chained
  14.     self :default(callback) - Sets the default callback
  15.  
  16.  
  17. EXAMPLE
  18.  
  19. local Switch = require(script.Switch)
  20.  
  21. local SpeedCase = Switch()
  22.     :case(16, function()
  23.         print("Hello Sixteen")
  24.     end)
  25.  
  26.     :case(30, function()
  27.         print("Hello Thirty")
  28.     end)
  29.  
  30.     :default(function()
  31.         print("Unrecognised")
  32.     end)
  33.  
  34. SpeedCase(script.Parent.Humanoid.WalkSpeed)
  35.  
  36. ]]--
  37.  
  38. local switchObjectMethods = {}
  39. switchObjectMethods.__index = switchObjectMethods
  40.  
  41. switchObjectMethods.__call = function(self, variable)
  42.     local c = self._callbacks[variable] or self._default
  43.     if not c then
  44.         error("No case statement defined for variable, and :default is not defined")
  45.     end
  46.    
  47.     c()
  48. end
  49.  
  50. function switchObjectMethods:case(v, f)
  51.     self._callbacks[v] = f
  52.     return self
  53. end
  54.  
  55. function switchObjectMethods:default(f)
  56.     self._default = f
  57.     return self
  58. end
  59.  
  60. -------------------------------------------------------------0
  61. return function()
  62.     local o = setmetatable({}, switchObjectMethods)
  63.     o._callbacks = {}  
  64.     return o
  65. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement