This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
HDeffo's profile picture

[Snippet] Switch statement

Started by HDeffo, 24 February 2016 - 06:43 AM
HDeffo #1
Posted 24 February 2016 - 07:43 AM
A friend of mine who I have been trying to get to switch over to Lua was busy complaining that there isn't a switch statement in the language. After trying and failing to convince him to just use if .. elseif. I resorted instead to just writing a switch statement for him. He didn't like this either though since it didn't handle regular expressions/patterns. Since I had to admit that would give it an advantage over normal if statements I ended up writing it. Here is the code snippet for anyone interested along with usage examples


local function switch(vInput) --#our function magic at work
return function(tCases)
  local sent = vInput
  if type(vInput) == "string" then
   for k,v in next, tCases do
	if type(k)=="string" then
	 local s, e = vInput:find(k)
	 if s==1 and e==#vInput then
	  vInput = k
	  break
	 end
	end
   end
  end
  if tCases[vInput] then
   tCases[vInput](sent)
  elseif tCases["_"..type(vInput)] then
   tCases["_"..type(vInput)](sent)
  elseif tCases._default then
   tCases._default(sent)
  end
end
end


--[[#
#thats the end of the snippet
#
#everything below is just example
#]]


function foo(bar) --#function to demonstate switches
   switch(bar) --#compare all cases to whatever was passed as bar
   {  
	  ["%d+"] = function(x) print(x..", is all digits") end; --#run if given string with all digits
  
	  ["%a+"] = function(x) print(x..", is all letters") end; --#run if given string with all letters
  
	  [5] = function(x) print(tostring(x)..", is numeral five") end; --#run if given five
  
	  _number = function(x) print(tostring(x)..", is a number but i know it isnt five") end; --#for any number not five
  
	  _table = function(x) print(tostring(x)..", well thats a table") end; --#run if given a table
  
	  _default = function(x) print(tostring(x)..", ...well we don't have a handle for this") end; --#run this if none of the rest were true
  
   }  
end

--#each of these will run through each case in order
foo("foobar")
foo("12345")
foo(5)
foo(95)
foo({"a table"})
foo("password1 is a very bad password")
Edited on 24 February 2016 - 06:46 AM
Lupus590 #2
Posted 24 February 2016 - 08:51 AM
the syntax is surprisingly pleasant, nice work but I think I'll stick with elseif in Lua
HDeffo #3
Posted 24 February 2016 - 10:08 AM
the syntax is surprisingly pleasant, nice work but I think I'll stick with elseif in Lua

Yeah I was kind of surprised myself of how much I could simplify the syntax after I started thinking on it.
apemanzilla #4
Posted 02 March 2016 - 03:52 PM
That's actually a really clever little syntax hack - I might try something like this myself, thanks!