Skip to content

Commit

Permalink
Merge pull request #6 from mah0x211/change-returns-index-funcs
Browse files Browse the repository at this point in the history
Change return values of the indexesof and indexof methods
  • Loading branch information
mah0x211 authored May 20, 2024
2 parents 295d775 + 2b11971 commit f3b6da2
Showing 1 changed file with 26 additions and 24 deletions.
50 changes: 26 additions & 24 deletions regex.lua
Original file line number Diff line number Diff line change
Expand Up @@ -201,56 +201,60 @@ end
--- indexesof
--- @param sbj string
--- @param offset? integer
--- @return integer[]? heads
--- @return integer[]? tails
--- @return integer[]? arr
--- @return any err
function Regex:indexesof(sbj, offset)
local head, tail, err = self.p:match_nocap(sbj, offset)

-- found
if head then
local heads = {}
local tails = {}
local arr = {}
local idx = 1

while head do
heads[idx], tails[idx] = head, tail
idx = idx + 1

arr[idx], arr[idx + 1] = head, tail
idx = idx + 2
head, tail, err = self.p:match_nocap(sbj, tail)
end

if err then
return nil, nil, err
return nil, err
end

return heads, tails
return arr
elseif err then
return nil, err
end

return nil, nil, err
end

--- indexof
--- @param sbj string
--- @param offset? integer
--- @return integer[]? heads
--- @return integer[]? tails
--- @return integer[]? arr
--- @return any err
function Regex:indexof(sbj, offset)
local heads, tails, err = self.p:match(sbj, offset or self.lastidx)

-- found
if heads then
local arr = {}
local idx = 1

for i = 1, #heads do
arr[idx], arr[idx + 1] = heads[i], tails[i]
idx = idx + 2
end

-- updaet a last-index if global option is enabled
if self.global == true then
self.lastidx = tails[1]
end
return heads, tails

return arr
elseif err then
return nil, err
elseif self.global then
-- reset a last-index to 0 if global option is enabled
self.lastidx = 0
end

return nil, nil, err
end

--- test
Expand Down Expand Up @@ -313,13 +317,12 @@ end
--- @param pattern string
--- @param flags? string
--- @param offset? integer
--- @return integer[]? heads
--- @return integer[]? tails
--- @return integer[]? arr
--- @return any err
local function indexesof(sbj, pattern, flags, offset)
local re, err = Regex(pattern, flags)
if err then
return nil, nil, err
return nil, err
end
return re:indexesof(sbj, offset)
end
Expand All @@ -329,13 +332,12 @@ end
--- @param pattern string
--- @param flags? string
--- @param offset? integer
--- @return integer[]? heads
--- @return integer[]? tails
--- @return integer[]? arr
--- @return any err
local function indexof(sbj, pattern, flags, offset)
local re, err = Regex(pattern, flags)
if err then
return nil, nil, err
return nil, err
end
return re:indexof(sbj, offset)
end
Expand Down

0 comments on commit f3b6da2

Please sign in to comment.