Skip to content

Commit 6d333b9

Browse files
committed
fix: is_array()
1 parent c4ec6a7 commit 6d333b9

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

arrays.lua

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,15 +118,37 @@ local function _cloned(o, deep)
118118
return o2
119119
end
120120

121-
function M.is_array(o)
121+
--- check if object is array-like
122+
--- object is array-like if it is a non-empty table and all keys are integers
123+
---@param o? any object to check
124+
---@param linear? boolean false to allow gaps between keys
125+
---@return boolean is_array true if object is non-empty and is array-like
126+
function M.is_array(o, linear)
122127
if type(o) ~= "table" then
123128
return false
124129
end
125-
local max_idx = 0
130+
131+
linear = linear ~= false
132+
if linear then
133+
local i = 1
134+
for _, _ in pairs(o) do
135+
if o[i] == nil then
136+
return false
137+
end
138+
i = i + 1
139+
end
140+
return i > 1 -- check for not empty
141+
end
142+
143+
local is_empty = true
126144
for i, _ in pairs(o) do
127-
max_idx = i
145+
if type(i) ~= "number" or math.floor(i) ~= i then
146+
return false
147+
end
148+
is_empty = false
128149
end
129-
return max_idx == #o
150+
151+
return not is_empty
130152
end
131153

132154
---@param items any[] array to read from

0 commit comments

Comments
 (0)