Module:FunList/Iterators: Difference between revisions

From Melvor Idle
No edit summary
No edit summary
Line 16: Line 16:


function Enumerator:moveNext()
function Enumerator:moveNext()
mw.log('calling broken func')
error('Not implemented in base class.')
error('Not implemented in base class.')
end
end
Line 22: Line 21:
-- Hooks the moveNext function into the Lua 'pairs' function
-- Hooks the moveNext function into the Lua 'pairs' function
function Enumerator:overridePairs()
function Enumerator:overridePairs()
mw.log('overriding pairs()')
self.index = nil
self.index = nil
self.current = nil
self.current = nil
Line 49: Line 47:


function TableEnumerator:moveNext()
function TableEnumerator:moveNext()
mw.log('calling override with')
mw.log('key: ' .. tostring(self.index))
mw.log('val: ' .. tostring(self.current))
-- Grab the next index for the internal table.
-- Grab the next index for the internal table.
local key = self.index
local key = self.index

Revision as of 16:07, 21 July 2024

Documentation for this module may be created at Module:FunList/Iterators/doc

-- BASE ENUMERATOR CLASS --
--enumerable = {}
local Enumerator = {}
local Enumerator_mt = {
	__index = Enumerator,
	__pairs = function(t) return t:overridePairs() end,
	--__ipairs = function(t) return t:overrideiPairs() end
}

function Enumerator.new()
	local self = setmetatable({}, Enumerator_mt)
	self.current = nil
	self.index = nil
	return self
end

function Enumerator:moveNext()
	error('Not implemented in base class.')
end

-- Hooks the moveNext function into the Lua 'pairs' function
function Enumerator:overridePairs()
	self.index = nil
	self.current = nil
	local function iterator(t, k)
		if self:moveNext() == true then
			return self.index, self.current
		end
		return nil, nil
	end
	
	return iterator, self, nil
end

-- TABLE ENUMERATOR CLASS --
-- This is essentially a wrapper for the table object, 
-- since it provides no state machine esque iteration out of the box
local TableEnumerator = setmetatable({}, { __index = Enumerator })
TableEnumerator.__index = TableEnumerator
TableEnumerator.__pairs = Enumerator_mt.__pairs

function TableEnumerator.new(tbl)
    local self = setmetatable(Enumerator.new(), TableEnumerator)
    self.data = tbl
    return self
end

function TableEnumerator:moveNext()
	-- Grab the next index for the internal table.
	local key = self.index
	key = next(self.data, key)
	self.index = key
	
	-- If the index exist, we have succesfuly moved to the next.
	if key ~= nil then
		self.current = self.data[key]
		return true
	end
	
	return false
end

return {
    Enumerator = Enumerator,
    TableEnumerator = TableEnumerator
}