The switch
library is a simple library used to create a C/C++ like switch case statement in Lua.
Lua does not have a stock method of implementing switch statements, thus this library can make that a possibility.
The switch
library is based on code by Ryan Hartlage
. https://github.com/ryanplusplus/switch.lua
Addons should require the common
library if they wish to use the switch
library. It is included automatically with it.
1require 'common';
switch
Implements a switch case style statement.
1any switch(value, cases);
Parameter Name | Type | Description |
---|---|---|
value | any | The conditional value to switch against. |
cases | table | The table of condition callback functions. |
Returns |
---|
(any | none) Any return as desired, or none. |
Below are a few examples of using switch
:
1-- Using a switch with a return value..
2function get_some_value(arg)
3 return switch(arg, T{
4 [0] = function () return 'Arg Was 0'; end,
5 [1] = function () return 'Arg Was 1'; end,
6 [switch.default] = function () return 'Arg Was Unknown'; end,
7 });
8end
9
10-- Using a switch with ranged cases..
11function get_some_value(arg)
12 return switch(arg, T{
13 [table.range(0, 5)] = function () return 'Arg Was 0, 1, 2, 3, 4 or 5'; end,
14 [6] = function () return 'Arg Was 6'; end,
15 [switch.default] = function () return 'Arg Was Unknown'; end,
16 });
17end
18
19-- Using a switch with string cases, no return value..
20function do_something(arg)
21 switch(arg, T{
22 ['one'] = function () call_one(); end,
23 ['two'] = function () call_two(); end,
24 ['three'] = function () call_three(); end,
25 [switch.default] = function () error('invalid case'); end,
26 });
27end