Module:FunList/Iterators

From Melvor Idle
< Module:FunList
Revision as of 14:55, 21 July 2024 by Ricewind (talk | contribs) (Created page with "enumerable = {} local enumerable = {} local enumerable_mt = { __index = enumerable, __pairs = function(t) return t:overridePairs()end } function enumerable.new(tbl) local self = setmetatable({}, enumerable_mt) self.data = tbl self.current = nil self.index = nil return self end function enumerable:moveNext() -- Grab the next index for the internal table. local ix = self.index ix = next(self.data, ix) self.index = ix -- If the index exist, we have succ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

enumerable = {}
local enumerable = {}
local enumerable_mt = {
	__index = enumerable,
	__pairs = function(t) return t:overridePairs()end
}

function enumerable.new(tbl)
	local self = setmetatable({}, enumerable_mt)
    
	self.data = tbl
	self.current = nil
	self.index = nil
	return self
end

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

function enumerable:overridePairs()
	self.index = nil
	self.current = nil
	local function iterator(t, k)
		if self:moveNext() == true then
			return self.index, self.current
		else
			return nil, nil
		end
	end
	
	return iterator, self, nil
end

return enumerable