C++ Switch Cases in lua?

I was wondering recently how switch case are implemented in C++. I found some similarities so I tried to implement them into lua

This is what I came up with

local Case = math.random(1,3)
local Switch = {
    [1] = function() 
        print(Case)
    end,
    [2] = function() 
        print(Case)
    end,
    [3] = function() 
        print(Case)
    end
}
Switch[Case]()

So now I’m wondering if it’s superior to conventional ifs or no

2 Likes

The reason why we use switch cases in languages like C++ is when we have too many conditions.
If you have, for example, 10 cases, it would be unoptimal and much harder to use else-if statements repeatedly and may even result in spaghetti code.
But writing it in the switch-case form allows for a more optimal way and easier readability for your code.

In your case though, the switch case is unneeded. You would be better off using else-if statements instead.
Also if you’re going to use this switch-case system, using for loops might be a better way for it.

3 Likes

lua already has it, its called elseif

3 Likes

That’s exactly why I did that. Elseif’s check step by step if the value is correct. Switch cases work differently. If oversimplified, it’s about getting the executable id with the value switch case was provided with. There would be a performance difference if put 100 elseif’s conditions and 100 switch case conditions. The switch case would instantly execute the required part of the code, elseif would loop through all it’s statements until the value matches.

1 Like

Also if I’m not mistaken most C++ Compilers now-a-days just compile a switch case into a bunch of if-else statements so there isn’t a computational boost in doing it.

2 Likes

oh man this is defo a pretty cool concept but

  1. you do need to find a way to implement default and
  2. if yer working in a team you gotta let them know youre gonna be using this pattern because the syntax is slightly scuffed and itll be a bit hard to adjust to lololol

also idk if this is superior ig this is a personal preference thing

1 Like

this one’s pretty possible

local Case = math.random(1,3)
local Switch = {
    [1] = function() 
        print(Case)
    end,
    [2] = function() 
        print(Case)
    end,
    [3] = function() 
        print(Case)
    end
    Default = function()
        print("no cases match")
    end
}
(Switch[Case] or Switch.Default)()

probably superior if there’s a giant chain of ifs and elseifs
but very tiny difference in any case so

3 Likes

For readability, and functionality you could use a module to create your own Switch statement if you really wanted to, I personally don’t see a reason for it but here.

Module

local Switch = {}
Switch.__index = Switch

function Switch.new(value)
	local self = setmetatable({}, Switch)
	self.value = value
	self.cases = {}
	self.defaultCase = nil
	return self
end

function Switch:case(val, func)
	table.insert(self.cases, {value = val, action = func})
	return self
end

function Switch:default(func)
	self.defaultCase = func
	return self
end

function Switch:execute()
	for _, case in ipairs(self.cases) do
		if case.value == self.value then
			case.action()
			return
		end
	end

	if self.defaultCase then
		self.defaultCase()
	end
end

return Switch

Script EXAMPLE

local Switch = require("Switch Module Directory")

local value = 25

local switch = Switch.new(value)
	:case(10, function()
		print("Case 10")
	end)
	:case(20, function()
		print("Case 20")
	end)
	:default(function()
		print("Default case")
	end)

switch:execute()

If I missed something let me know.

1 Like

I think everyone here is missing a key important but sometimes unintended result of using switches: fallthrough. Fallthrough has some pretty handy use cases (even if rare) and a lot of these posts are basically just making redesigned if statements, not actual switches.

1 Like

What about pass through, else if can barely do that

1 Like

Luau if statements will still be better. In your example, you’re allocating memory for the table, which the GC then has to clean up. This will happen every time you run the switch case, unless you’re caching it.

I benchmarked this. If you are creating the ‘Switch’ table every time, then it is significantly slower than if statements. If you cache the ‘Switch’ table, then it is significantly faster, but if statements are still fastest.

6 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.