模块:TowerTable
外观
local p = {}
local cfg = {
wrapStyle = 'overflow-x:auto;width:100%;',
tableStyle = 'background-color:#212121;color: #EAECF0;white-space: nowrap;',
defaultClass = 'wikitable',
firstHeader = "'''防御塔等级与属性项(总和)'''",
errCategory = '[[Category:防御塔表格需要修复]]',
}
local function trim(s)
return mw.text.trim(s or '')
end
function p.main(frame)
local args = frame:getParent().args
local class = args.class or cfg.defaultClass
local headerStr = args.header or ""
local rowsStr = args.rows or ""
local footerStr = args.footer or ""
local issues = {}
if trim(headerStr) == '' then
return cfg.errCategory
end
-- 1. 解析列标题
local headers = {}
for h in mw.text.gsplit(headerStr, ",") do
table.insert(headers, mw.text.trim(h))
end
local ncol = #headers
if ncol == 0 then
return cfg.errCategory
end
-- 2. 解析数据行
local rows = {}
for row in mw.text.gsplit(rowsStr, ";") do
local cells = {}
for cell in mw.text.gsplit(row, ",") do
table.insert(cells, mw.text.trim(cell))
end
if #cells > 0 and trim(row) ~= "" then
table.insert(rows, cells)
end
end
-- 3. 构建原始 wikitext 表格字符串
local tableText = '<div style="' .. cfg.wrapStyle .. '">\n{| class="' .. class .. '" style="' .. cfg.tableStyle .. '"\n'
-- 表头行
tableText = tableText .. '| ' .. cfg.firstHeader
for _, h in ipairs(headers) do
tableText = tableText .. ' || {{c|' .. h .. '|' .. h .. '}}'
end
tableText = tableText .. '\n'
-- 数据行
for _, rowCells in ipairs(rows) do
local firstColRaw = rowCells[1] or ""
if firstColRaw:match('^{{') then
-- 模板标签(如 {{twtl|...}})自行输出行分隔符,保持原样
tableText = tableText .. firstColRaw .. '\n'
else
-- 纯文本标签:由模块补 |- 和单元格前缀,缺少 twtl 也能成立
local label = firstColRaw:gsub('^|%-%s*', '')
tableText = tableText .. '|-\n| ' .. label .. '\n'
end
for i = 2, #rowCells do
local header = headers[i - 1]
if header == nil then
issues[#issues + 1] = 'extra-cell'
break
end
local cellValue = rowCells[i] or ""
tableText = tableText .. (i == 2 and '| ' or ' || ') .. '{{c|' .. header .. '|' .. cellValue .. '}}'
end
-- 列数不足时补空单元格,避免整行错位
if #rowCells - 1 < ncol then
issues[#issues + 1] = 'missing-cell'
for i = #rowCells + 1, ncol + 1 do
tableText = tableText .. (i == 2 and '| ' or ' || ') .. '{{c|' .. headers[i - 1] .. '|}}'
end
end
tableText = tableText .. '\n'
end
-- 脚注行
if footerStr ~= "" then
tableText = tableText .. '|-\n'
tableText = tableText .. '| ' .. footerStr .. '\n'
end
tableText = tableText .. '|}\n</div>'
-- 4. 解析整个表格字符串
local out = frame:preprocess(tableText)
if #issues > 0 then
out = out .. cfg.errCategory
end
return out
end
return p