Anonymous

Module:FunList/Iterators: Difference between revisions

From Melvor Idle
no edit summary
No edit summary
No edit summary
Line 24: Line 24:
self.current = nil
self.current = nil
self.index = nil
self.index = nil
-- Assume by default we are not dealing with a simple array
self.isArray = false
return self
return self
end
end
Line 31: Line 33:
end
end


function Enumerator:getEnumerator()
function Enumerator:getEnumerator(startIndex)
error('Not implemented in base class.')
error('Not implemented in base class.')
end
end
Line 38: Line 40:
function Enumerator:overridePairs(startIndex)
function Enumerator:overridePairs(startIndex)
-- Get or create clean enumerator. This ensures the state is 0.
-- Get or create clean enumerator. This ensures the state is 0.
local enum = self:getEnumerator()
local enum = self:getEnumerator(startIndex)
enum.current = nil
enum.current = nil
enum.index = startIndex
enum.index = startIndex
Line 56: Line 58:
local TableEnumerator = setmetatable({}, { __index = Enumerator })
local TableEnumerator = setmetatable({}, { __index = Enumerator })
TableEnumerator.__index = TableEnumerator
TableEnumerator.__index = TableEnumerator
TableEnumerator.__pairs = Enumerator_mt.__pairs
TableEnumerator.__pairs = Enumerator_mt.__pairs
TableEnumerator.__ipairs = Enumerator_mt.__ipairs


function TableEnumerator.new(tbl)
function TableEnumerator.new(tbl)
Line 63: Line 66:
     self.tbl = tbl
     self.tbl = tbl
     self.state = 0
     self.state = 0
    self.startIndex = nil


     return self
     return self
Line 71: Line 73:
     if self.state == 0 then
     if self.state == 0 then
         self.state = 1
         self.state = 1
        self.startIndex = self.index
     end
     end


     if self.startIndex == 0 then
     if self.isArray == true then
         -- Iterate using ipairs, starting from index 1
         -- Iterate using ipairs, starting from index 1
         self.index = self.index + 1
         self.index = self.index + 1
Line 93: Line 94:
end
end


function TableEnumerator:getEnumerator()
-- startIndex is used to determine if the underlying table should be treated
-- as an array or as a mixed table. It is ignored in the other enumerators as
-- they just call moveNext on the enumerator instead.
function TableEnumerator:getEnumerator(startIndex)
local instance = nil
if self.state == 0 then
if self.state == 0 then
return self
instance = self
else
else
return TableEnumerator.new(self.tbl)
instance = TableEnumerator.new(self.tbl)
end
end
mw.log(startIndex == 0)
instance.isArray = startIndex == 0
return instance
end
end


2,875

edits