Is there a Switch-block equivalent?

So in C#, there is something called “the switch block”
pretty much a better if elseif elseif elseif elseif else statement.
it goes like this:

//C#
string MyString = "Hello"

switch(MyString)
{
  case "apple":
    Console.WriteLine("First case");
    break;
  case "String":
   Console.WriteLine("Second Case");
   break;
  case "Hello":
   Console.WriteLine("HIIIII");
   break;
  default:
   Console.WriteLine("No matches have been found :(");
   break;
}

i would like to know this, since i don’t want to be typing if, elseif , elseif ,elseif, every time…
the switch block is primarily made to take an object and compare it against other objects, as you can see in the example i provided. if no matches are found it runs default, unless there’s none.
so i wonder if lua has this?
because right now this is what the lua equivalent would look like without using the switch block:

--Lua
local Mystring = "hello"

if Mystring == "apple" then
 print("Case one")
elseif Mystring == "String" then
 print("Case two")
elseif Mystring == "hello" then
 print("HIIIII")
else
 print("No matches have been found :(")
end

for me this is way more to type, but it could just be my lazyness acting up again …
so do you know if a lua equivalent switch block exists?

Thanks in advance!

There’s no direct luau equivalent, but you can always just write modules that can achieve the same functionality. For example,

Yeah, use tables:

local MyString = "Hello"
({
	Apple = function()
		print("Apple")
	end,
	String = function()
		print("String")
	end,
	Hello = function()
		print("Hello")
	end,
})[MyString]()

The default case can be implemented using metatables:

local function switch(tbl)
	local mt = {__index=function() return tbl.default end}
	setmetatable(tbl, mt)
	return tbl
end

local MyString = "abc"

switch({
	Apple = function()
		print("Apple")
	end,
	String = function()
		print("String")
	end,
	Hello = function()
		print("Hello")
	end,
	default = function()
		print("Default")
	end,
})[MyString]()

Thanks for coming to my TED talk, I’m happy to showcase my deep and extensive lua knowledge (not to brag).

I’m stupid. You can also just:

local function switch(val)
	return function(tbl)
		if tbl[val] == nil then
			return tbl.default()
		else
			tbl[val]()
		end
	end
end

local MyString = "abc"

switch(MyString) {
	Hello = function()
		print("Hello")
	end,
	Apple = function()
		print("Apple")
	end,
	String = function()
		print("String")
	end,
	default = function()
		print("Default")
	end
}
1 Like