For those of you who don’t know what a switch case is, it’s just an easier way of writing if-else statements but fancier. Except mine attempts to make these if-else statements shorter.
Im not gonna lie, even though I tested this, I barley tested it to the fullest. I’m not sure if this is even worth making I might call it quits…
local module = {}
-- After sending the first two parameteres for the given module function, the rest are indexed seperately.
-- Meaning that the index of the first case you provided versus the second case are both index 1.
-- With the exception that after the second case is established, the index will then start iterating
-- forwards IF you provide additional ones. Going 1, 2, 3, 4 index... to illustrate this textually below...
-- (data, [1]value, func, [1]value2, func, [2]value3, func, [3]value4, func, etc...)
function module.FunctionalSwitchCase(data : any, caseValue : any, func: any, ...)
local additionalCases = {...}
if data then
if data == caseValue then
func()
return 1, caseValue
else
for i,v in pairs(additionalCases) do
if i/2 ~= math.floor(i) and data == v then
additionalCases[i+1]()
return i, v
elseif i == #additionalCases then
return i, nil
else
continue
end
end
end
end
end
function module.ReturnSwitchCase(data : any, caseValue: any, ...)
local additionalCases = {...}
if data then
if data == caseValue then
return 1, true
else
for i,v in pairs(additionalCases) do
if data == v then
return i, true
elseif i == #additionalCases then
return i, nil
else
continue
end
end
end
end
end
return module
TESTING ON SERVER SCRIPT
--[[Tested On ServerScript]]
local module = require(script.Parent)
--FunctionSwitchCase, activate functions based on values.
local function prototypeAlien()
print("Why Aliens?")
end
local function prototypeMonster()
print("Why Monsters?")
end
local function prototypeCookie()
print("Why Cookies?")
end
local prototypeValue_1 = "Aliens"
local index, value = module.FunctionalSwitchCase(prototypeValue_1, "Aliens", prototypeAlien, "Monsters", prototypeMonster, "Cookies", prototypeCookie)
print(index, value)
---ReturnSwtichCase, return true or nil statements.
local prototypeValue_2 = 4
local index_2, value_2 = module.ReturnSwitchCase(prototypeValue_2, 5, 2, 3, 5, 6, 8, 9, 10, 15, 4)
print(index_2, value_2)