theTANCO

switch.lua

Jul 28th, 2021
821
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- This function attempts to emulate switch statements used in programming languages such as C++.
  2. -- First argument is the case in the statement to run. This is a value to index an element in a table. Indexes can be any number or string.
  3. -- Second argument is a table containing functions representing each case. This only executes the case indexed by the first argument. Setting a case equal to a number or string represents a pointer to a different case function. This is to avoid copy and pasting functions. Pointers cannot point to pointers. Unlike C++ switch statements, these switch statements can be nested within switch statements.
  4. -- Third argument is the default case. This is run if none of the other cases are executed.
  5. -- Additional arguments are passed to the case functions.
  6. switch = function(case, cases, defCase, ...)
  7.     if cases[case] then
  8.         if type(cases[case]) == "function" then return cases[case](...)
  9.         elseif type(cases[case]) == "number" or type(cases[case]) == "string" then return cases[cases[case] ](...)
  10.         else error("Case element must be a number, string, or function.", 2) end
  11.     else return defCase(...) end
  12. end
  13.  
  14. -- Examples of the switch statement in use.
  15. local function testProgram()
  16.     for a = 0, 5 do
  17.         switch(a, {
  18.             [0] = function()
  19.                 print('h')
  20.             end,
  21.             [1] = function()
  22.                 print('e')
  23.             end,
  24.             [2] = function()
  25.                 print('l')
  26.             end,
  27.             [3] = 2,
  28.             [4] = function()
  29.                 print('o')
  30.             end
  31.         }, function(punctuation)
  32.             print(punctuation)
  33.         end, '.')
  34.     end
  35.  
  36.     switch("pear", {
  37.         ["apple"] = function()
  38.             print("Hello world")
  39.         end,
  40.         pear = function()
  41.             print("Switch statements are neat.")
  42.         end
  43.     }, function() end)
  44.  
  45.     switch("apple", {
  46.         ["fruit"] = function()
  47.             print("Hello world")
  48.         end,
  49.         veggie = function()
  50.             print("Switch statements are neat.")
  51.         end,
  52.         apple = "fruit"
  53.     }, function() end)
  54. end
  55.  
  56. -- Uncomment the line below to run the test program function.
  57. -- testProgram()
RAW Paste Data