Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/stein197/lua-switch
Switch statement for Lua
https://github.com/stein197/lua-switch
Last synced: 12 days ago
JSON representation
Switch statement for Lua
- Host: GitHub
- URL: https://github.com/stein197/lua-switch
- Owner: stein197
- License: mit
- Created: 2021-11-27T12:43:24.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2021-12-30T12:46:24.000Z (almost 3 years ago)
- Last Synced: 2024-08-01T19:57:42.396Z (3 months ago)
- Language: Lua
- Size: 4.88 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Switch expression statement for Lua
[![](https://img.shields.io/github/license/stein197/lua-switch)](LICENSE)
![](https://img.shields.io/github/v/tag/stein197/lua-switch?label=Version)
[![](https://img.shields.io/luarocks/v/stein197/lua-switch)](https://luarocks.org/modules/stein197/lua-switch)
[![](https://img.shields.io/github/size/stein197/lua-switch/init.lua)](init.lua)This package provides simple function named "switch" which could be used to emulate switch statement which does not exist in Lua but does in other languages. It can handle default fallback.
## Installation
Via LuaRocks:
```
luarocks install lua-switch
```
Or just download and require `init.lua` file from this repo.## Usage
Just require it in the code like in the example below:
```lua
local switch, default = require "lua-switch"()
local var = "b"
switch (var) {
a = 1; -- Use string key
[1] = 2; -- Or numeric one
[{"b", "c"}] = function () -- Use multiple values. Mostly functions will be used as code block
print "Switch!" -- Prints "Switch!"
end;
[default] = function () -- Use default fallback
var = 12
end
}
-- Or even use it as expression
local var = switch "b" {
a = 1;
b = 2;
c = 3;
d = function ()
return 4; -- If you wish you can also use function blocks and return values from them
end;
}
print(var) -- Prints "2"
```## Testing
Install luaunit package:
```
luarocks install luaunit
```
Then run from the console:
```
lua test.lua
```
Make sure that `luaunit` package can be required using `package.path` variable.