Module:TechLister/Prereqs

From Terra Invicta Official Wiki

Documentation for this module may be created at Module:TechLister/Prereqs/doc

---
---Reads the Tech data files and computes a table of prereqs

--region Dependencies
local TechData = mw.loadData('Module:CSVReader/Tech')
--endregion

--region Private constants
--endregion

--region Private member variables
local prereqTable = {}
local doneTechs = {}
--endregion

--region Private methods
function fillPrereqs(techID)
	if doneTechs[techID] then
		-- This means this function has previously already filled the prereqs for this tech.
		-- Nothing further needs to be done.
		return true
	elseif prereqTable[techID] then 
		-- This means this function previously considered this tech, yet did not fill the prereqs for it. 
		-- This is impossible without a loop in the tech tree.
		mw.log("Attempt to build Tech tree found a loop.")
		return false
	end	
	
	prereqTable[techID] = {}
	for i = 0, 2 do
		local prereq = TechData[techID]['prereqs/' .. i]
		if prereq and prereq ~= '' and prereq ~= 0 then
			-- Add this direct prereq as a prereq for techID.
			prereqTable[techID][prereq] = true
			-- Fill the prereqs for this direct prereq.
			if not fillPrereqs(prereq) then
				return false
			end
			-- Add every prereq of this direct prereq as a prereq for techID.
			for rowID, b in pairs(prereqTable[prereq]) do
				prereqTable[techID][rowID] = true
			end
		end
	end
	doneTechs[techID] = true
	return true
end

function getPrereqTable()
	for rowID, row in pairs(TechData) do
		if not fillPrereqs(rowID) then
			return {} -- Abort
		end
	end
	return prereqTable
end

--endregion

--region Public methods
--endregion

return getPrereqTable()