Jump to content

Module:LogicUtils

From Logic World Wiki
Revision as of 11:46, 8 September 2025 by Felipe (talk | contribs) (use mw.html instead of raw html strings)

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

local p = {}

function parse_io(kind, row, str)
	local count = tonumber(str)
	local names = {}

	if count == nil then
		-- str is a list of IO names
		names = mw.text.split(str, ",")
	else
		-- str is a number
		if count == 1 then
			names[1] = kind
		else
			for i=1,count do
				names[i] = string.format("%s %i", kind, i)
			end
		end
	end

	for i, v in ipairs(names) do
		row:tag('th')
			:wikitext(v)
	end

	return #names
end

p.truth_table = function(frame, args)
	local args = args or frame:getParent().args

    local tbl = mw.html.create('table')
        :addClass('wikitable')

	if args.caption ~= nil then
		tbl:tag('caption')
			:wikitext(args.caption)
	end

    local header = tbl:tag('tr')
	local nInputs = parse_io("Input", header, args.inputs)
	local nOutputs = parse_io("Output", header, args.outputs)

	local i = 1
	while args[i] ~= nil do
		local row = tbl:tag('tr')

		local ioCounter = 1
		for token in string.gmatch(args[i], "[^%s]+") do
			local style = "color:white; text-align:center;"
			if token == "0" then
				row:tag('td')
					:attr('style', 'background-color:#1f1e1e;'..style)
					:wikitext("0")
			elseif token == "1" then
				row:tag('td')
					:attr('style', 'background-color:#fd140f;'..style)
					:wikitext("1")
			else
				row:tag('td')
					:wikitext(token)
			end
			ioCounter = ioCounter + 1
		end
		
		i = i + 1
	end

    return tostring(tbl)
end


return p