Module:Sandbox/marius851000/wikitable3d

From Wikidata
Jump to navigation Jump to search
Lua
CodeDiscussionLinksLink count SubpagesDocumentationTestsResultsSandboxLive code All modules

WIP -- currently only 2d (ps: the 3d is because there are row, column, and possibly multiple value per case. Use Mkey, but will probably reconsider this)

Code

local mkey = require("Module:Sandbox/marius851000/mkey");

local tableContain = function(array, value)
	for _, v in ipairs(array) do
		if (v == value) then
			return true
		end
	end
	return false
end

local tableRemove = function(array, value)
	for c = 1, #array do
		if (array[c] == value) then
			table.remove(array, c);
			return
		end
	end
end

local escape = function(text)
	return string.gsub(text, "\n", "<br />") --TODO: pretty bad escape method
end

r = {}

r.formatTable = function(tableData, columnOrder, rowOrder, label)
	if (tableData == nil) then
		error("tableData may not be nil");
	end
	if (columnOrder == nil) then
		columnOrder = {};
	end
	if (rowOrder == nil) then
		rowOrder = {};
	end
	if (label == nil) then
		label = "";
	end
	-- sort by something, as it may otherwise be non-deterministic
	-- order the key and values, ensuring that columnOrder and rowOrder are complete
	for rowKey, rowValue in pairs(tableData) do
		if (not tableContain(rowOrder, rowKey)) then
			table.insert(rowOrder, rowKey);
		end
		for columnKey, _ in pairs(rowValue) do
			if (not tableContain(columnOrder, columnKey)) then
				table.insert(columnOrder, columnKey)
			end
		end
	end
	-- put unknown values at the end of the table
	if (tableContain(rowOrder, mkey.unknownMkey())) then
		tableRemove(rowOrder, mkey.unknownMkey());
		table.insert(rowOrder, mkey.unknownMkey());
	end
	if (tableContain(columnOrder, mkey.unknownMkey())) then
		tableRemove(columnOrder, mkey.unknownMkey());
		table.insert(columnOrder, mkey.unknownMkey());
	end
	
	result = "{| class=\"wikitable\"\n";
	result = result .. "|-\n";
	-- create the header
	result = result .. "! " .. label .. " ";
	for _, columnKey in ipairs(columnOrder) do
		result = result .. "!! " .. escape(mkey.mkeyToText(columnKey)) .. " "
	end
	result = result .. "\n"
	-- create all the rows
	for _, rowKey in ipairs(rowOrder) do
		result = result .. "|-\n"
		result = result .. "| " .. escape(mkey.mkeyToText(rowKey)) .. " "
		for _, columnKey in ipairs(columnOrder) do
			key = tableData[rowKey][columnKey];
			if (key == nil) then
				key = mkey.unknownMkey()
			end
			result = result .. "|| " .. escape(mkey.mkeyToText(key))
		end
		result = result .. '\n'
	end
	result = result .. "|}\n"
	
	return result
end

return r