A small module for creating a switch case simulation with Builder syntax.
This attempts to mirror the behaviour of switch case statements in Visual Basic.
Returns a function which can be used for constructing switch case objects (see example)
Switch Case Object
Metamethods
__call (when it is called like a function) - Runs the switch case statement
Example:
SwitchCase(n) --n is the variable to be checked against the condition
Properties: dictionary _callbacks - A storage table used for holding the callbacks function _default - The default function for undefined conditions
Methods: SwitchCaseObject case(value, callback) - binds a callback to specified value.
WARNING: This function has only been tested on strings and numbers, it may behave weirdly with other datatypes
SwitchCaseObject default(callback) - binds the default function to a callback
Example
Below is an example for Switch
local Switch = require(script.Switch) --Load the Switch module
local newConditional = Switch() --Create a new SwitchCase using builder syntax
:case("Player1", function() --Setup a case value callback
print("Player 1 is outstanding")
end)
:case("Player2", function()
print("Player 2 is amazing")
end)
:default(function() --allows you to manage undefined conditions. SwitchCase will error if this is not declared and you use an invalid value
print("not declared")
end)
local Player1Name = "Player1"
local Player2Name = "Player2"
local unwantedValue = false
newConditional(Player1Name) --> Player 1 is outstanding
newConditional(Player2Name) --> Player 2 is amazing
newConditional(unwantedValue) --> not declared
Since this uses callbacks instead of it being a statement, break statements dont need to be used, I already knew most other languages with this implementation use break part of it’s statement.
It’s not worth implementing something like this if it’s unnecessary and may affect performance.
Edit: annnd I reply to the wrong person again. Sorry about that!
You could pass a controller object through that would indicate to the switch object to skip the remaining cases when invoked. Ex:
--Values passed through 'resolve' would be returned instead of what the actual function may return (similar to how promises work)
Switch()
:case('Player1', function(resolve)
--do stuff
resolve(...)
end)
I only suggest this up because multi-case operations would be a nice addition that would reduce boilerplate code.