模块:层级表

来自希服维基
跳到导航 跳到搜索

可在模块:层级表/doc创建此模块的帮助文档

local getArgs = require('Module:Arguments').getArgs
local p = {}

function p._main(args)
	local s = "{|"
	if args.class then
		s=s.. 'class="' .. mw.text.nowiki(args.class) .. '"'
	end
	local cells = {}
	local row = 1
	local last_col = 0
	local max_col = 1
	for _, arg in ipairs(args) do
		if arg and arg ~= "" then
			if arg:sub(1, 1) == "+" then
				s=s.. "\n|" .. arg
			elseif arg:sub(1, 1) == "!" then
				s=s.. "\n" .. arg
			else
				local stars, text = arg:match("(%**)(.+)")
				local col = #stars + 1
				if col > max_col then
					max_col = col
				elseif col <= last_col then
					row = row + 1
				end
				table.insert(cells, { row=row, col=col, text=text })
				last_col = col
			end
		end
	end
	local max_row = row
	local last_row = 0
	for i, cell in ipairs(cells) do
		local row = cell.row
		local col = cell.col
		local row2 = max_row
		local col2 = max_col
		if i < #cells and cells[i + 1].row == row then
			col2 = cells[i + 1].col - 1
		end
		for j = i + 1, #cells do
			if cells[j].row > row and cells[j].col <= col2 then
				row2 = cells[j].row - 1
				break
			end
		end
		local rowspan = row2 - row + 1
		local colspan = col2 - col + 1
		if row > last_row then
			s=s.. '\n|-style="vertical-align:top"'
		end
		s=s.. "\n|"
		if rowspan ~= 1 then
			s=s.. " rowspan=" .. rowspan
		end
		if colspan ~= 1 then
			s=s.. " colspan=" .. colspan
		end
		s=s.. "|" .. cell.text
		last_row = row
	end
	s=s.. "\n|}"
	return s
end

function p.main(frame)
	local args = getArgs(frame, {
		removeBlanks=false,
		wrappers={ "模板:层级表" },
	})
	return p._main(args)
end

return p