Anonymous

Module:FunList/Iterators: Difference between revisions

From Melvor Idle
no edit summary
No edit summary
No edit summary
Line 4: Line 4:
local Enumerator_mt = {
local Enumerator_mt = {
__index = Enumerator,
__index = Enumerator,
__pairs = function(t) return t:overridePairs()end
__pairs = function(t) return t:overridePairs() end,
__ipairs = function(t) return t:overrideiPairs() end
}
}


Line 18: Line 19:
end
end


function Enumerator:moveINext()
error('Not implemented in base class.')
end
-- Hooks the moveNext function into the Lua 'pairs' function
function Enumerator:overridePairs()
function Enumerator:overridePairs()
self.index = nil
self.current = nil
local function iterator(t, k)
local function iterator(t, k)
if self:moveNext() == true then
if self:moveNext() == true then
return self.index, self.current
return self.index, self.current
else
return nil, nil
end
end
return nil, nil
end
end
self.index = nil
self.current = nil
return iterator, self, nil
return iterator, self, nil
end
-- Hooks the moveNext function into the Lua 'ipairs' function
function Enumerator:overrideiPairs()
    local function iterator(t, k)
    if self:moveINext() == true then
    return self.index, self.current
    end
    return nil, nil
    end
   
    self.index = 0
    self.current = nil
    return iterator, self, self.index
end
end


Line 51: Line 70:
-- If the index exist, we have succesfuly moved to the next.
-- If the index exist, we have succesfuly moved to the next.
if key then
if key ~= nil then
self.current = self.data[key]
self.current = self.data[key]
return true
end
return false
end
function TableEnumerator:moveINext()
self.index = self.index + 1
self.current = self.data[self.index]
if self.current ~= nil then
return true
return true
end
end
2,875

edits