跳转到内容

模块:TowerTable/sandbox

来自Minimalist Tower Defense Wiki
Jathonbot​(留言 | 贡献)2026年11月25日 (三) 10:44的版本 (沙盒:完整改进版(纯文本标签 + 列数校验 + 兜底))

此模块的文档可以在模块:TowerTable/sandbox/doc创建

local p = {}

local cfg = {
    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 "wikitable"
    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

    local headers = {}
    for h in mw.text.gsplit(headerStr, ",") do
        table.insert(headers, mw.text.trim(h))
    end
    if #headers == 0 then
        return cfg.errCategory
    end

    local rows = {}
    for row in mw.text.gsplit(rowsStr, ";") do
        if trim(row) ~= "" then
            local cells = {}
            for cell in mw.text.gsplit(row, ",") do
                table.insert(cells, mw.text.trim(cell))
            end
            if #cells > 0 then
                table.insert(rows, cells)
            end
        end
    end

    local tableText = '<div style="overflow-x:auto;width:100%;">\n{| class="' .. class .. '" style="background-color:#212121;color: #EAECF0;white-space: nowrap;"\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 ""
        local markup = firstColRaw:match('^%s*|') or firstColRaw:match('^%s*!') or firstColRaw:match('^{{')
        if markup then
            tableText = tableText .. firstColRaw .. '\n'
        else
            tableText = tableText .. '|-\n| ' .. firstColRaw:gsub('^|%-%s*', '') .. '\n'
        end

        for i = 2, #rowCells do
            local header = headers[i - 1]
            if header == nil then
                issues[#issues + 1] = 'extra-cell'
                break
            end
            tableText = tableText .. (i == 2 and '| ' or ' || ') .. '{{c|' .. header .. '|' .. (rowCells[i] or '') .. '}}'
        end

        if #rowCells - 1 < #headers then
            issues[#issues + 1] = 'missing-cell'
            for i = #rowCells + 1, #headers + 1 do
                tableText = tableText .. (i == 2 and '| ' or ' || ') .. '{{c|' .. headers[i - 1] .. '|}}'
            end
        end

        tableText = tableText .. '\n'
    end

    if footerStr ~= "" then
        tableText = tableText .. '|-\n| ' .. footerStr .. '\n'
    end

    tableText = tableText .. '|}\n</div>'

    local out = frame:preprocess(tableText)
    if #issues > 0 then
        out = out .. cfg.errCategory
    end
    return out
end

return p