Module:FunList/Iterators: Difference between revisions

Add SelectEnumerator
No edit summary
(Add SelectEnumerator)
Line 16: Line 16:


function Enumerator:moveNext()
function Enumerator:moveNext()
error('Not implemented in base class.')
end
function Enumerator:getEnumerator()
error('Not implemented in base class.')
error('Not implemented in base class.')
end
end
Line 42: Line 46:
function TableEnumerator.new(tbl)
function TableEnumerator.new(tbl)
     local self = setmetatable(Enumerator.new(), TableEnumerator)
     local self = setmetatable(Enumerator.new(), TableEnumerator)
     self.data = tbl
     self.tbl = tbl
     return self
     return self
end
end


function TableEnumerator:moveNext()
function TableEnumerator:moveNext()
if self.state == 0 then
self.state = 1
end
-- Grab the next index for the internal table.
-- Grab the next index for the internal table.
local key = self.index
local key = self.index
key = next(self.data, key)
key = next(self.tbl, key)
self.index = key
self.index = key
-- If the index exist, we have succesfuly moved to the next.
-- If the index exist, we have succesfuly moved to the next.
if key ~= nil then
if key ~= nil then
self.current = self.data[key]
self.current = self.tbl[key]
return true
return true
end
end
return false
return false
end
function TableEnumerator:getEnumerator()
if self.state == 0 then
return self
else
return TableEnumerator.new(self.tbl)
end
end
-- SELECT ENUMERATOR --
local SelectEnumerator = setmetatable({}, { __index = Enumerator })
SelectEnumerator.__index = SelectEnumerator
SelectEnumerator.__pairs = Enumerator_mt.__pairs
function SelectEnumerator.new(source, selector)
    local self = setmetatable(Enumerator.new(), TableEnumerator)
    self.state = 0
    self.source = source
    self.selector = selector
    self.enumerator = nil
    self.position = 0
    return self
end
function SelectEnumerator:moveNext()
if self.state == 0 then
self.state = 1
self.position = 0
self.enumerator = self.source:getEnumerator()
end
if self.state == 1 then
local enumerator = self.enumerator
if enumerator:moveNext() == true then
local sourceElement = enumerator.current
self.position = self.position + 1
self.current = selector(sourceElement, self.position)
return true
end
end
return false
end
function SelectEnumerator:getEnumerator()
if self.state == 0 then
return self
else
return SelectEnumerator.new(self.source, self.selector)
end
end
end


2,875

edits