Skip to content

Commit

Permalink
fix(utils.enum) don't allow varargs with nils
Browse files Browse the repository at this point in the history
  • Loading branch information
Tieske committed Feb 13, 2022
1 parent 4ea8dae commit 57253b2
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
3 changes: 0 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,13 @@ deprecation policy.
see [CONTRIBUTING.md](CONTRIBUTING.md#release-instructions-for-a-new-version) for release instructions

## 1.13.0 (unreleased)
<<<<<<< HEAD
- fix: `compat.warn` raised write guard warning in OpenResty
[#414](https://github.com/lunarmodules/Penlight/pull/414)
=======
- feat: `utils.enum` now accepts hash tables, to enable better error handling
[#413](https://github.com/lunarmodules/Penlight/pull/413)
- feat: `utils.kpairs` new iterator over all non-integer keys
[#413](https://github.com/lunarmodules/Penlight/pull/413)

>>>>>>> b38c390 (feat(utils) enum to accept hash tables as well)

## 1.12.0 (2022-Jan-10)
- deprecate: module `pl.text` the contents have moved to `pl.stringx` (removal later)
Expand Down
20 changes: 9 additions & 11 deletions lua/pl/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ function utils.enum(...)
if type(first) ~= "table" then
-- vararg with strings
lst = utils.pack(...)
for i, value in ipairs(lst) do
for i, value in utils.npairs(lst) do
utils.assert_arg(i, value, "string")
enum[value] = value
end
Expand All @@ -378,17 +378,15 @@ function utils.enum(...)
enum[value] = value
end
-- add key-ed part
for key, value in pairs(first) do
if not lst[key] then
if type(key) ~= "string" then
error(("expected key to be 'string' but got '%s'"):format(type(key)), 2)
end
if enum[key] then
error(("duplicate entry in array and hash part: '%s'"):format(key), 2)
end
enum[key] = value
lst[#lst+1] = key
for key, value in utils.kpairs(first) do
if type(key) ~= "string" then
error(("expected key to be 'string' but got '%s'"):format(type(key)), 2)
end
if enum[key] then
error(("duplicate entry in array and hash part: '%s'"):format(key), 2)
end
enum[key] = value
lst[#lst+1] = key
end
end

Expand Down
4 changes: 4 additions & 0 deletions spec/utils-enum_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ describe("pl.utils", function ()
assert.has.error(function()
t = enum("hello", true, "world")
end, "argument 2 expected a 'string', got a 'boolean'")
-- no holes
assert.has.error(function()
t = enum("hello", nil, "world")
end, "argument 2 expected a 'string', got a 'nil'")
end)


Expand Down

0 comments on commit 57253b2

Please sign in to comment.