2,875
edits
No edit summary |
No edit summary |
||
Line 17: | Line 17: | ||
__index = Enumerator, | __index = Enumerator, | ||
__pairs = function(t) return t:overridePairs() end, | __pairs = function(t) return t:overridePairs() end, | ||
__ipairs = function(t) return t:overridePairs(0) end | |||
} | } | ||
Line 62: | Line 62: | ||
local self = setmetatable(Enumerator.new(), TableEnumerator) | local self = setmetatable(Enumerator.new(), TableEnumerator) | ||
self.tbl = tbl | self.tbl = tbl | ||
self.state = 0 | |||
-- We base the behaviour of moveNext on self.index! | |||
-- If self.index is set to 0, it's ipairs, otherwise it's pairs | |||
if self.index == 0 then | |||
self.moveNext = TableEnumerator.pairsMoveNext | |||
else | |||
self.moveNext = TableEnumerator.ipairsMoveNext | |||
end | |||
end | end | ||
function TableEnumerator: | function TableEnumerator:moveNextPairs() | ||
if self.state == 0 then | if self.state == 0 then | ||
self.state = 1 | self.state = 1 | ||
Line 78: | Line 85: | ||
if key ~= nil then | if key ~= nil then | ||
self.current = self.tbl[key] | self.current = self.tbl[key] | ||
return true | |||
end | |||
return false | |||
end | |||
function TableEnumerator:moveNextIPairs() | |||
if self.state == 0 then | |||
self.state = 1 | |||
end | |||
-- Grab the next index for the internal table. | |||
self.index = self.index + 1 | |||
self.current = self.tbl[self.index] | |||
-- If the index exist, we have succesfuly moved to the next. | |||
if self.current ~= nil then | |||
return true | return true | ||
end | end |
edits