-
Notifications
You must be signed in to change notification settings - Fork 5
switch
A library giving the ability to create code with switch-like statements.
In contrast to switch...case statements in C, there is no flow or fallthrough in this implementation. Executing a case will only ever execute that particular case, or the default case if there is no case with the specified identifier.
The library returns a table which can be called as a function; taking a case table as its argument, and returning a new switch object with the specified case table.
Argument name | Type | Description |
---|---|---|
case table |
table | a table of cases |
- Create a new switch with an empty case table.
local myswitch = switch{}
- Create a new switch with a populated case table.
local myswitch = switch{
[1] = "case one",
[2] = "case two",
default = "default case"
}
- Add a case to the case table.
myswitch[3] = "case three"
- Add a case as a function to the case table.
myswitch[4] = function()
return "case four"
end
- Add a case with additional parameters to the case table.
myswitch[5] = function(...)
return "case five\n"..save_table{...}
end
There are three methods for executing a case.
- Calling the switch object's
case
function - Calling the switch object itself
- Using array syntax on the switch object
Each methods requires passing at the very least one argument; the identifier for the case to execute.
Method 1 and 2 supports additional parameters; passed to the case if it is a function; or ignored if it is not.
If the case table has no case for the specified case identifier, the default
case will be executed.
- Execute a case by calling 'case'.
LOG(myswitch:case(1))
- The function
case
supports additional arguments; passed to the case function for the specified case identifier.
LOG(myswitch:case(1, "argument1", "argument2", ...))
- Execute a case by simply calling the switch object. This is equivalent to using the function
case
above.
LOG(myswitch(1))
- This method also supports additional arguments.
LOG(myswitch(1, "argument1", "argument2", ...))
- Execute a case using array syntax. This is equivalent to the previous two methods, except it does not support passing of additional arguments like them.
LOG(myswitch[1])