Anonymous

Module:FunList/Iterators: Difference between revisions

From Melvor Idle
no edit summary
No edit summary
No edit summary
Line 37: Line 37:
-- Hooks the moveNext function into the Lua 'pairs' function
-- Hooks the moveNext function into the Lua 'pairs' function
function Enumerator:overridePairs(startIndex)
function Enumerator:overridePairs(startIndex)
-- Get or create clean enumerator
-- Get or create clean enumerator. This ensures the state is 0.
local enum = self:getEnumerator()
local enum = self:getEnumerator()
enum.current = nil
enum.current = nil
Line 63: Line 63:
     self.tbl = tbl
     self.tbl = tbl
     self.state = 0
     self.state = 0
     self.startIndex = self.index
     self.startIndex = nil


     return self
     return self
Line 69: Line 69:


function TableEnumerator:moveNext()
function TableEnumerator:moveNext()
if self.state == 0 then
    if self.state == 0 then
self.state = 1
        self.state = 1
end
        self.startIndex = self.index
    end
-- if startIndex is 0, it means we are dealing with a ipairs() iteration since the initial index for this
 
-- iteration has to start at 0. Otherwise, we are dealing with a pairs() iteration.
    if self.startIndex == 0 then
if self.startIndex == 0 then
        -- Iterate using ipairs, starting from index 1
-- Grab the next index for the internal table.
        self.index = self.index + 1
self.index = self.index + 1
        self.current = self.tbl[self.index]
self.current = self.tbl[self.index]
        return self.current ~= nil
-- If the index exist, we have succesfuly moved to the next.
    else
if self.current ~= nil then
        -- Iterate using pairs
return true
        local key = self.index
end
        key = next(self.tbl, key)
else
        self.index = key
-- Grab the next index for the internal table.
        if key ~= nil then
local key = self.index
            self.current = self.tbl[key]
key = next(self.tbl, key)
            return true
self.index = key
        end
if key ~= nil then
    end
self.current = self.tbl[key]
return true
end
end


return false
    return false
end
end


2,875

edits