Skip to content

Commit

Permalink
Adding valid.func() to check if a value is a function
Browse files Browse the repository at this point in the history
  • Loading branch information
benwilber committed May 19, 2024
1 parent 2c0dd4f commit 830cc07
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ A library for Lua to validate various values and table structures.
- [`valid.arrayof`](#validarrayof)
- [`valid.map`](#validmap)
- [`valid.mapof`](#validmapof)
- [`valid.func`](#validfunc)
- [Error Handling and Invalid Propagation](#error-handling-and-invalid-propagation)
- [Contributing](#contributing)
- [License](#license)
Expand Down Expand Up @@ -384,6 +385,28 @@ assert(not is_valid) -- false, "name" is required for "bob"
* `empty`: Set to `true` to allow empty maps.
* `func`: A table containing two custom validation functions, one for the keys and one for the values.

### `valid.func`

Validates that a value is a function.

#### Usage

```lua
local valid = require "valid"

local valid_function = valid.func()

local is_valid = valid_function(function() end)
assert(is_valid) -- true

local is_valid = valid_function("123")
assert(not is_valid) -- false, not a function
```

#### Parameters

*(none)*

## Error Handling and Invalid Propagation

The library provides detailed error information when validation fails. When `is_valid` is `false`, additional values are provided to help identify the nature of the validation failure:
Expand Down
28 changes: 28 additions & 0 deletions tests.lua
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,35 @@ describe("Validation Library Tests", function()
}
}

local simple_function = function() end

local tests = {
-- Valid simple function
{
description = "Valid simple function",
definition = valid.func(),
data = simple_function,
expected = {
is_valid = true,
val_or_err = simple_function,
badval_or_nil = nil,
path_or_nil = nil
}
},

-- Invalid function
{
description = "Invalid function",
definition = valid.func(),
data = "123",
expected = {
is_valid = false,
val_or_err = "func",
badval_or_nil = "123",
path_or_nil = nil
}
},

-- Valid contact data
{
description = "Valid contact data",
Expand Down
11 changes: 11 additions & 0 deletions valid.lua
Original file line number Diff line number Diff line change
Expand Up @@ -339,4 +339,15 @@ local function mapof(deffuncs, opts)
end
_M.mapof = mapof

local function func()
return function(val)
if type(val) ~= "function" then
return false, "func", val
end

return true, val
end
end
_M.func = func

return _M

0 comments on commit 830cc07

Please sign in to comment.