Skip to content

Lua library that provides a powerful pattern-matching function to handle complex cases based on different conditions, such as values, ranges, and table comparisons.

Notifications You must be signed in to change notification settings

jigordev/lua-match

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Lua-Match

lua-match is a Lua library that provides a powerful pattern-matching function to handle complex cases based on different conditions, such as values, ranges, and table comparisons.

Installation

To use lua-match in your Lua project, you can install library using luarocks.

luarocks install lua-match

Usage

Function Signature

match(value, cases)
  • value: The value that will be checked against the cases.
  • cases: A table containing the patterns and corresponding actions. The keys of this table can be values, ranges, tables, or functions, and the values are the functions to be executed if the condition matches.

Example

local match = require("match").match
local range = require("match").range

-- Define cases with different conditions
local result1 = match(10, {
    [1] = function() return "Value is 1" end,
    [range(5, 15)] = function() return "Value is between 5 and 15" end,
    ["_"] = function() return "Value not found" end
})

print(result1)  -- Output: "Value is between 5 and 15"

local result2 = match(3, {
    [1] = function() return "Value is 1" end,
    [range(5, 15)] = function() return "Value is between 5 and 15" end,
    ["_"] = function() return "Value not found" end
})

print(result2)  -- Output: "Value not found"

How It Works

  • String, Number, or Boolean Key: When a string, number, or boolean is used as the key in the cases table, it checks if the value matches the key and then executes the corresponding function.

  • Range (Range Check): If the key for a range function, the library validates that the value is within the specified range.

  • Table Key (Equality Check): If the table is not a range, it checks if the table matches the value exactly (using deep comparison).

  • Function Key: If the key is a function, the function is called with the value. If the result matches the value or evaluates to true, the corresponding action is executed.

  • Middleclass Instance: Receives the middleclass class as a key and checks whether the value is an instance of the class.

  • Fallback (_): If none of the conditions match, the function defined in the _ key is executed (or a default action of returning nil).

License

This library is available under the MIT License. See the LICENSE file for more details.

About

Lua library that provides a powerful pattern-matching function to handle complex cases based on different conditions, such as values, ranges, and table comparisons.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages