Switch Statements Module

Hello people of DevForum! I would like to make a few things clear before I showcase my module:

  • I’m aware this has been made many times before
  • I did not make this to be used practically, but for fun
  • You can use this wherever you want, anyone could have made this

Switch Statements Module

Module Code
local module = {}


function module.Switch(arg: any, cases: {})
	for caseval, func in cases do
		
		if arg ~= caseval then continue end
		
		func()
		
	end
end

return module

To initiate a Switch statement, you must give two arguments. The first argument is the variable to check, and the second argument is a key-value dictionary. Each key must be the Case you are checking for, and the Value a function().

Example of how to use the module:

for Counter = 1, 3 do
	module.Switch(Counter, {
		[1] = function()
			print("It's one!")
		end,
		
		[2] = function()
			print("Wow, it's two?")
		end,
		
		[3] = function()
			print("Would you know it! It's THREE!")
		end,

		["Hello World"] = function()
			warn("It's not meant to be a string!!!")
		end,
	})
end

Get the module?

Keep in mind, this is all a bit of fun! :tongue:

It would be nice if this module could execute multiple functions until something like break is encountered and had a default case, just like switch statements in Java and other languages.

I understand what you mean by a default case, but I think i might need elaboration on what “execute multiple functions” means

  • Doing more than one check per statement - This is implemented!
  • Looping a function multiple times: Use a For loop inside the function

Switch statements usually fall through multiple cases until it encounters a break or return.

1 Like

would be nice if the syntax was:

switch(i) {
  [1] = function()
    print(i +1)
  end
}

but this is cool anyways

1 Like