Jump to content

Module:GearSet: Difference between revisions

From EverQuest Legends Wiki
Created page with "local p = {} local NUMERIC_COLUMNS = { { key = 'ac', header = 'AC', labels = { 'AC' } }, { key = 'hp', header = 'HP', labels = { 'HP' } }, { key = 'mana', header = 'Mana', labels = { 'MANA' } }, { key = 'endurance', header = 'End', labels = { 'ENDURANCE', 'ENDUR', 'END' } }, { key = 'str', header = 'STR', labels = { 'STR' } }, { key = 'sta', header = 'STA', labels = { 'STA' } }, { key =..."
 
No edit summary
Line 1: Line 1:
local p = {}
local p = {}
------------------------------------------------------------------------
-- Column configuration
------------------------------------------------------------------------


local NUMERIC_COLUMNS = {
local NUMERIC_COLUMNS = {
     { key = 'ac',       header = 'AC',     labels = { 'AC' } },
    -- Combat vitality
     { key = 'hp',       header = 'HP',     labels = { 'HP' } },
     {
     { key = 'mana',     header = 'Mana',   labels = { 'MANA' } },
        key = 'ac',
     { key = 'endurance', header = 'End',     labels = { 'ENDURANCE', 'ENDUR', 'END' } },
        header = 'AC',
        labels = { 'AC' },
    },
     {
        key = 'hp',
        header = 'HP',
        labels = { 'HP' },
    },
     {
        key = 'mana',
        header = 'MANA',
        labels = { 'MANA' },
    },
     {
        key = 'endurance',
        header = 'END',
        labels = {
            'ENDURANCE',
            'ENDUR',
            'END',
        },
    },


     { key = 'str',       header = 'STR',     labels = { 'STR' } },
    -- Base attributes
     { key = 'sta',       header = 'STA',     labels = { 'STA' } },
     {
     { key = 'dex',       header = 'DEX',     labels = { 'DEX' } },
        key = 'str',
     { key = 'agi',       header = 'AGI',     labels = { 'AGI' } },
        header = 'STR',
     { key = 'cha',       header = 'CHA',     labels = { 'CHA' } },
        labels = { 'STR' },
     { key = 'wis',       header = 'WIS',     labels = { 'WIS' } },
    },
     { key = 'int',       header = 'INT',     labels = { 'INT' } },
     {
        key = 'sta',
        header = 'STA',
        labels = { 'STA' },
    },
     {
        key = 'int',
        header = 'INT',
        labels = { 'INT' },
    },
     {
        key = 'wis',
        header = 'WIS',
        labels = { 'WIS' },
    },
     {
        key = 'agi',
        header = 'AGI',
        labels = { 'AGI' },
    },
     {
        key = 'dex',
        header = 'DEX',
        labels = { 'DEX' },
    },
     {
        key = 'cha',
        header = 'CHA',
        labels = { 'CHA' },
    },


     { key = 'svmagic',   header = 'SV MAG', labels = { 'SV MAGIC', 'SV MAG' } },
    -- Resistances
     { key = 'svfire',   header = 'SV FIRE', labels = { 'SV FIRE' } },
     {
     { key = 'svcold',   header = 'SV COLD', labels = { 'SV COLD' } },
        key = 'mr',
     { key = 'svdisease', header = 'SV DIS', labels = { 'SV DISEASE', 'SV DIS' } },
        header = 'MR',
     { key = 'svpoison', header = 'SV POI', labels = { 'SV POISON', 'SV POI' } },
        labels = {
            'SV MAGIC',
            'SV MAG',
            'MR',
        },
    },
     {
        key = 'fr',
        header = 'FR',
        labels = {
            'SV FIRE',
            'FR',
        },
    },
     {
        key = 'cr',
        header = 'CR',
        labels = {
            'SV COLD',
            'CR',
        },
    },
     {
        key = 'dr',
        header = 'DR',
        labels = {
            'SV DISEASE',
            'SV DIS',
            'DR',
        },
    },
     {
        key = 'pr',
        header = 'PR',
        labels = {
            'SV POISON',
            'SV POI',
            'PR',
        },
    },
    {
        key = 'vr',
        header = 'VR',
        labels = {
            'SV VR',
            'VR',
        },
    },
}
}
local TOTAL_COLUMN_COUNT =
    2 +                  -- Item and Slot
    #NUMERIC_COLUMNS +
    4                    -- Haste, Weight, Effect, Dropped By
------------------------------------------------------------------------
-- General helpers
------------------------------------------------------------------------


local function trim(value)
local function trim(value)
Line 28: Line 138:
local function escapePattern(value)
local function escapePattern(value)
     return (
     return (
         value:gsub(
         tostring(value or ''):gsub(
             '([%^%$%(%)%%%.%[%]%*%+%-%?])',
             '([%^%$%(%)%%%.%[%]%*%+%-%?])',
             '%%%1'
             '%%%1'
Line 35: Line 145:
end
end


-- Reads the arguments inside the page's {{Itempage ...}} invocation.
local function formatPlainNumber(value)
-- It respects nested templates, wiki links, and wiki tables so pipes
    if value == nil then
-- inside those constructs are not mistaken for Itempage parameters.
        return ''
    end
 
    if math.floor(value) == value then
        return tostring(math.floor(value))
    end
 
    local formatted = string.format('%.2f', value)
 
    formatted = formatted:gsub('0+$', '')
    formatted = formatted:gsub('%.$', '')
 
    return formatted
end
 
local function formatHaste(value)
    if value == nil then
        return ''
    end
 
    local formatted = formatPlainNumber(value)
 
    if value > 0 then
        return '+' .. formatted .. '%'
    end
 
    return formatted .. '%'
end
 
local function formatWeight(value)
    if value == nil then
        return ''
    end
 
    local formatted = string.format('%.2f', value)
 
    formatted = formatted:gsub('0+$', '')
    formatted = formatted:gsub('%.$', '')
 
    -- Preserve the familiar EverQuest weight style:
    -- 2 becomes 2.0, while 0.1 remains 0.1.
    if not formatted:find('%.', 1, true) then
        formatted = formatted .. '.0'
    end
 
    return formatted
end
 
------------------------------------------------------------------------
-- Itempage template parser
------------------------------------------------------------------------
 
-- Reads the named arguments inside the first {{Itempage ...}} invocation.
--
-- This parser keeps track of nested templates, wiki links, and wiki tables,
-- preventing internal pipes from being mistaken for Itempage parameters.
local function parseItempageParameters(content)
local function parseItempageParameters(content)
     local startPosition = content:find('{{%s*[Ii]tempage[%s|]')
     local startPosition =
        content:find('{{%s*[Ii]tempage[%s|]')


     if not startPosition then
     if not startPosition then
Line 56: Line 222:


     while position <= contentLength do
     while position <= contentLength do
         local pair = content:sub(position, position + 1)
         local pair =
         local character = content:sub(position, position)
            content:sub(position, position + 1)
 
         local character =
            content:sub(position, position)


         if pair == '{{' then
         if pair == '{{' then
             curlyDepth = curlyDepth + 1
             curlyDepth = curlyDepth + 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


         elseif pair == '}}' then
         elseif pair == '}}' then
             if curlyDepth == 1 then
             if curlyDepth == 1 then
                 table.insert(segments, table.concat(buffer))
                 table.insert(
                    segments,
                    table.concat(buffer)
                )
 
                 break
                 break
             end
             end


             curlyDepth = curlyDepth - 1
             curlyDepth = curlyDepth - 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


         elseif pair == '[[' then
         elseif pair == '[[' then
             squareDepth = squareDepth + 1
             squareDepth = squareDepth + 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


         elseif pair == ']]' and squareDepth > 0 then
         elseif pair == ']]' and squareDepth > 0 then
             squareDepth = squareDepth - 1
             squareDepth = squareDepth - 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


         elseif pair == '{|' then
         elseif pair == '{|' then
             tableDepth = tableDepth + 1
             tableDepth = tableDepth + 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


         elseif pair == '|}' and tableDepth > 0 then
         elseif pair == '|}' and tableDepth > 0 then
             tableDepth = tableDepth - 1
             tableDepth = tableDepth - 1
             table.insert(buffer, pair)
             table.insert(buffer, pair)
             position = position + 2
             position = position + 2


Line 99: Line 284:
             and tableDepth == 0
             and tableDepth == 0
         then
         then
             table.insert(segments, table.concat(buffer))
             table.insert(
                segments,
                table.concat(buffer)
            )
 
             buffer = {}
             buffer = {}
             position = position + 1
             position = position + 1


         else
         else
             table.insert(buffer, character)
             table.insert(buffer, character)
             position = position + 1
             position = position + 1
         end
         end
Line 115: Line 306:
     local parameters = {}
     local parameters = {}


     -- Segment 1 is the template name itself.
     -- Segment 1 contains the template name.
     for index = 2, #segments do
     for index = 2, #segments do
         local parameterName, parameterValue =
         local parameterName, parameterValue =
             segments[index]:match('^%s*([%w_%-]+)%s*=(.*)$')
             segments[index]:match(
                '^%s*([%w_%-]+)%s*=(.*)$'
            )


         if parameterName then
         if parameterName then
             parameters[parameterName:lower()] = trim(parameterValue)
             parameters[parameterName:lower()] =
                trim(parameterValue)
         end
         end
     end
     end
Line 127: Line 321:
     return parameters
     return parameters
end
end
------------------------------------------------------------------------
-- Page loading
------------------------------------------------------------------------


local function getPageContent(pageName)
local function getPageContent(pageName)
     local title = mw.title.new(pageName)
     local title = mw.title.new(pageName)


     -- Follow a few ordinary redirect pages.
     -- Follow ordinary redirects.
     for _ = 1, 4 do
     for _ = 1, 4 do
         if not title then
         if not title then
Line 143: Line 341:
         end
         end


         local redirectTarget = content:match(
         local redirectTarget =
            '^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*%[%[([^%]|#]+)'
            content:match(
        )
                '^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]' ..
                '%s*%[%[([^%]|#]+)'
            )


         if not redirectTarget then
         if not redirectTarget then
Line 151: Line 351:
         end
         end


         title = mw.title.new(trim(redirectTarget))
         title = mw.title.new(
            trim(redirectTarget)
        )
     end
     end


     return nil
     return nil
end
end
------------------------------------------------------------------------
-- Statsblock parsing
------------------------------------------------------------------------


local function normalizeStatsblock(statsblock)
local function normalizeStatsblock(statsblock)
Line 162: Line 368:
     stats = stats:gsub('\r\n', '\n')
     stats = stats:gsub('\r\n', '\n')
     stats = stats:gsub('\r', '\n')
     stats = stats:gsub('\r', '\n')
    -- Remove comments.
     stats = stats:gsub('<!%-%-.-%-%->', '')
     stats = stats:gsub('<!%-%-.-%-%->', '')
     stats = stats:gsub('<[bB][rR]%s*/?%s*>', '\n')
 
    -- Convert every form of <br> into a real line ending.
     stats = stats:gsub(
        '<[bB][rR]%s*/?%s*>',
        '\n'
    )
 
     stats = stats:gsub('&nbsp;', ' ')
     stats = stats:gsub('&nbsp;', ' ')
     stats = stats:gsub('[ \t]+\n', '\n')
     stats = stats:gsub('[ \t]+\n', '\n')
Line 170: Line 384:
end
end


local function extractNumber(statsblock, labels)
local function extractNumericValue(
     local uppercaseStats = statsblock:upper()
    statsblock,
    labels,
    allowDecimal
)
     local uppercaseStats =
        tostring(statsblock or ''):upper()
 
    local valuePattern
 
    if allowDecimal then
        valuePattern =
            '([%+%-]?%d+%.?%d*)'
    else
        valuePattern =
            '([%+%-]?%d+)'
    end


     for _, label in ipairs(labels) do
     for _, label in ipairs(labels) do
         local pattern =
         local pattern =
             escapePattern(label:upper()) ..
             escapePattern(label:upper()) ..
             '%s*:%s*([%+%-]?%d+)'
             '%s*:%s*' ..
            valuePattern


         local value = uppercaseStats:match(pattern)
         local value =
            uppercaseStats:match(pattern)


         if value then
         if value then
Line 186: Line 417:


     return nil
     return nil
end
-- Returns every line value matching one of the supplied labels.
--
-- Example:
-- Effect: [[Swift Spirit]] (Worn)
--
-- returns:
-- [[Swift Spirit]] (Worn)
local function extractLabeledLines(
    statsblock,
    labels
)
    local results = {}
    local seen = {}
    for line in tostring(statsblock or ''):gmatch('[^\n]+') do
        local cleanLine = trim(line)
        local uppercaseLine = cleanLine:upper()
        for _, label in ipairs(labels) do
            local pattern =
                '^' ..
                escapePattern(label:upper()) ..
                '%s*:%s*'
            local _, valueStart =
                uppercaseLine:find(pattern)
            if valueStart then
                local value =
                    trim(
                        cleanLine:sub(
                            valueStart + 1
                        )
                    )
                if value ~= ''
                    and not seen[value]
                then
                    seen[value] = true
                    table.insert(
                        results,
                        value
                    )
                end
                break
            end
        end
    end
    return results
end
end


local function extractLine(statsblock, labels)
local function extractLine(statsblock, labels)
     local uppercaseStats = statsblock:upper()
     local values =
        extractLabeledLines(
            statsblock,
            labels
        )
 
    return values[1] or ''
end
 
------------------------------------------------------------------------
-- Effects
------------------------------------------------------------------------
 
local function buildEffect(
    parameters,
    statsblock
)
    local results = {}
    local seen = {}
 
    local function addEffect(value)
        value = trim(value)
 
        if value == ''
            or seen[value]
        then
            return
        end
 
        seen[value] = true
 
        table.insert(results, value)
    end
 
    --------------------------------------------------------------------
    -- Explicit statsblock effects
    --------------------------------------------------------------------
 
    local explicitEffects =
        extractLabeledLines(
            statsblock,
            {
                'Effect',
                'Click Effect',
                'Worn Effect',
                'Proc Effect',
                'Combat Effect',
            }
        )
 
    for _, effect in ipairs(explicitEffects) do
        addEffect(effect)
    end
 
    --------------------------------------------------------------------
    -- Focus effect parameter
    --------------------------------------------------------------------
 
    local focusEffect =
        trim(parameters.focus_effect)
 
    if focusEffect ~= '' then
        if focusEffect:find('%[%[') then
            addEffect(
                'Focus: ' .. focusEffect
            )
        else
            addEffect(
                'Focus: [[' ..
                focusEffect ..
                ']]'
            )
        end
    end


     for _, label in ipairs(labels) do
     --------------------------------------------------------------------
        local pattern =
    -- Passive regeneration effects
            escapePattern(label:upper()) ..
    --------------------------------------------------------------------
            '%s*:%s*'


         local _, valueStart = uppercaseStats:find(pattern)
    local passiveEffectLabels = {
        'HP Regen',
        'Mana Regen',
         'Endurance Regen',
    }


         if valueStart then
    for _, label in ipairs(
            local lineEnd =
         passiveEffectLabels
                 statsblock:find('\n', valueStart + 1, true) or
    ) do
                 (#statsblock + 1)
        local values =
            extractLabeledLines(
                 statsblock,
                 { label }
            )


             return trim(
        for _, value in ipairs(values) do
                 statsblock:sub(valueStart + 1, lineEnd - 1)
             addEffect(
                 label .. ': ' .. value
             )
             )
         end
         end
     end
     end


     return ''
     return table.concat(results, '<br>')
end
end
------------------------------------------------------------------------
-- Drop-source extraction
------------------------------------------------------------------------


local function extractDropMobs(dropsfrom)
local function extractDropMobs(dropsfrom)
     local drops = tostring(dropsfrom or '')
     local drops =
        tostring(dropsfrom or '')


     drops = drops:gsub('\r\n', '\n')
     drops = drops:gsub('\r\n', '\n')
Line 223: Line 594:


     for line in drops:gmatch('[^\n]+') do
     for line in drops:gmatch('[^\n]+') do
         local mob = line:match('^%s*%*+%s*(.-)%s*$')
         local mob =
            line:match(
                '^%s*%*+%s*(.-)%s*$'
            )


         if mob and mob ~= '' and not seen[mob] then
         if mob
            and mob ~= ''
            and not seen[mob]
        then
             seen[mob] = true
             seen[mob] = true
             table.insert(results, mob)
             table.insert(results, mob)
         end
         end
Line 234: Line 612:
end
end


local function buildEffect(parameters, statsblock)
------------------------------------------------------------------------
    local results = {}
-- Item rendering and loading
------------------------------------------------------------------------


    local regularEffect = extractLine(
local function createHoverLink(
        statsblock,
    frame,
        {
    pageName
            'CLICK EFFECT',
)
            'WORN EFFECT',
     local success, rendered =
            'EFFECT',
         pcall(
        }
            function()
    )
                return frame:preprocess(
 
                    '{{:' .. pageName .. '}}'
     if regularEffect ~= '' then
                )
         table.insert(results, regularEffect)
            end
    end
 
    local focusEffect = trim(parameters.focus_effect)
 
    if focusEffect ~= '' then
        table.insert(
            results,
            'Focus: [[' .. focusEffect .. ']]'
         )
         )
    end


     return table.concat(results, '<br>')
     if success
end
         and trim(rendered) ~= ''
 
    then
local function createHoverLink(frame, pageName)
    local success, rendered = pcall(
        function()
            return frame:preprocess('{{:' .. pageName .. '}}')
         end
    )
 
    if success and trim(rendered) ~= '' then
         return rendered
         return rendered
     end
     end
Line 276: Line 638:
end
end


local function readItem(frame, pageName)
local function readItem(
     local content = getPageContent(pageName)
    frame,
    pageName
)
     local content =
        getPageContent(pageName)


     if not content then
     if not content then
         return nil, 'Item page does not exist or could not be read.'
         return nil,
            'Item page does not exist or could not be read.'
     end
     end


     local parameters = parseItempageParameters(content)
     local parameters =
        parseItempageParameters(content)


     if not parameters then
     if not parameters then
         return nil, 'No Itempage template was found on the item page.'
         return nil,
            'No Itempage template was found on the item page.'
     end
     end


     local statsblock = normalizeStatsblock(parameters.statsblock)
     local statsblock =
        normalizeStatsblock(
            parameters.statsblock
        )


     if statsblock == '' then
     if statsblock == '' then
         return nil, 'The item has no statsblock.'
         return nil,
            'The item has no statsblock.'
     end
     end


     local item = {
     local item = {
         pageName = pageName,
         pageName = pageName,
         itemName = trim(parameters.itemname) ~= ''
 
         itemName =
            trim(parameters.itemname) ~= ''
             and trim(parameters.itemname)
             and trim(parameters.itemname)
             or pageName,
             or pageName,


         hover = createHoverLink(frame, pageName),
         hover =
         slot = extractLine(statsblock, { 'SLOT' }),
            createHoverLink(
         effect = buildEffect(parameters, statsblock),
                frame,
         droppedBy = extractDropMobs(parameters.dropsfrom),
                pageName
            ),
 
         slot =
            extractLine(
                statsblock,
                { 'Slot' }
            ),
 
        haste =
            extractNumericValue(
                statsblock,
                { 'Haste' },
                true
            ),
 
        weight =
            extractNumericValue(
                statsblock,
                {
                    'WT',
                    'Weight',
                },
                true
            ),
 
         effect =
            buildEffect(
                parameters,
                statsblock
            ),
 
         droppedBy =
            extractDropMobs(
                parameters.dropsfrom
            ),
     }
     }


     for _, column in ipairs(NUMERIC_COLUMNS) do
     for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
         item[column.key] =
         item[column.key] =
             extractNumber(statsblock, column.labels)
             extractNumericValue(
                statsblock,
                column.labels,
                false
            )
     end
     end


Line 315: Line 731:
end
end


local function addCell(row, value, alignLeft)
------------------------------------------------------------------------
-- HTML table helpers
------------------------------------------------------------------------
 
local function addCell(
    row,
    value,
    alignLeft
)
     local cell = row:tag('td')
     local cell = row:tag('td')


     if alignLeft then
     if alignLeft then
         cell:css('text-align', 'left')
         cell:css(
            'text-align',
            'left'
        )
     end
     end


     if value ~= nil and value ~= '' then
     if value ~= nil
         cell:wikitext(tostring(value))
        and value ~= ''
    then
         cell:wikitext(
            tostring(value)
        )
    end
 
    return cell
end
 
local function addNumericCell(
    row,
    numericValue,
    displayedValue
)
    local cell = row:tag('td')
 
    if numericValue ~= nil then
        cell:attr(
            'data-sort-value',
            tostring(numericValue)
        )
 
        cell:wikitext(
            displayedValue
                or formatPlainNumber(
                    numericValue
                )
        )
     end
     end


Line 329: Line 784:
end
end


local function renderTable(frame, args, itemNames)
local function addHeader(
     local output = mw.html.create('table')
    row,
    text,
    colspan
)
    local header = row:tag('th')
 
    header:attr(
        'scope',
        colspan and 'colgroup' or 'col'
    )
 
    if colspan then
        header:attr(
            'colspan',
            colspan
        )
    end
 
    header:wikitext(text)
 
    return header
end
 
------------------------------------------------------------------------
-- Table rendering
------------------------------------------------------------------------
 
local function renderTable(
    frame,
    args,
    itemNames
)
     local output =
        mw.html.create('table')


     output
     output
         :addClass('wikitable')
         :addClass('wikitable')
         :addClass('sortable')
         :addClass('sortable')
        :addClass('eql-gear-set-table')
         :css('text-align', 'center')
         :css('text-align', 'center')
    --------------------------------------------------------------------
    -- Caption
    --------------------------------------------------------------------


     local caption = trim(args.caption)
     local caption = trim(args.caption)


     if caption == '' then
     if caption == '' then
         caption = 'List of items considered part of this set'
         caption = trim(args.name)
    end
 
    if caption == '' then
        caption =
            mw.title.getCurrentTitle().text
     end
     end


     output:tag('caption'):wikitext(caption)
     output
        :tag('caption')
        :wikitext(caption)
 
    --------------------------------------------------------------------
    -- Group headings
    --------------------------------------------------------------------


     local groupRow = output:tag('tr')
     local groupRow = output:tag('tr')
     groupRow
     groupRow
         :addClass('sortbottom')
         :addClass('sortbottom')
         :css('font-weight', 'bold')
         :css('font-weight', 'bold')


     groupRow:tag('th')
     addHeader(
         :attr('colspan', 2)
        groupRow,
         :wikitext('Item Info')
         'Item Info',
        2
    )
 
    addHeader(
        groupRow,
         'Combat Vitality',
        4
    )


     groupRow:tag('th')
     addHeader(
         :attr('colspan', 4)
        groupRow,
         :wikitext('Combat Vitality')
         'Base Attributes',
         7
    )


     groupRow:tag('th')
     addHeader(
         :attr('colspan', 7)
        groupRow,
         :wikitext('Base Attributes')
         'Resistances',
         6
    )


     groupRow:tag('th')
     addHeader(
         :attr('colspan', 5)
        groupRow,
         :wikitext('Resistances')
         'Miscellaneous',
         4
    )


     groupRow:tag('th')
     --------------------------------------------------------------------
        :attr('colspan', 2)
    -- Column headings
        :wikitext('Miscellaneous')
    --------------------------------------------------------------------


     local headerRow = output:tag('tr')
     local headerRow = output:tag('tr')


     headerRow:tag('th'):wikitext('Slot')
     addHeader(headerRow, 'Item')
     headerRow:tag('th'):wikitext('Item Name')
     addHeader(headerRow, 'Slot')


     for _, column in ipairs(NUMERIC_COLUMNS) do
     for _, column in ipairs(
         headerRow:tag('th'):wikitext(column.header)
        NUMERIC_COLUMNS
    ) do
         addHeader(
            headerRow,
            column.header
        )
     end
     end


     headerRow:tag('th'):wikitext('Effect')
     addHeader(headerRow, 'Haste')
     headerRow:tag('th'):wikitext('Dropped By')
    addHeader(headerRow, 'Weight')
     addHeader(headerRow, 'Effect')
    addHeader(headerRow, 'Dropped By')
 
    --------------------------------------------------------------------
    -- Totals
    --------------------------------------------------------------------


     local totals = {}
     local totals = {}


     for _, column in ipairs(NUMERIC_COLUMNS) do
     for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
         totals[column.key] = 0
         totals[column.key] = 0
     end
     end
    local totalWeight = 0
    local bestHaste = nil
    --------------------------------------------------------------------
    -- Item rows
    --------------------------------------------------------------------


     for _, pageName in ipairs(itemNames) do
     for _, pageName in ipairs(itemNames) do
         local item, errorMessage = readItem(frame, pageName)
         local item, errorMessage =
            readItem(
                frame,
                pageName
            )


         if not item then
         if not item then
             local errorRow = output:tag('tr')
             local errorRow =
                output:tag('tr')


             errorRow:tag('td')
             errorRow
                 :attr('colspan', 20)
                :tag('td')
                 :attr(
                    'colspan',
                    TOTAL_COLUMN_COUNT
                )
                 :addClass('error')
                 :addClass('error')
                 :css('text-align', 'left')
                 :css(
                    'text-align',
                    'left'
                )
                 :wikitext(
                 :wikitext(
                     '[[' .. pageName .. ']]: ' .. errorMessage
                     '[[' ..
                    pageName ..
                    ']]: ' ..
                    errorMessage
                 )
                 )
         else
         else
             local row = output:tag('tr')
             local row = output:tag('tr')


             addCell(row, item.slot, true)
             addCell(
             addCell(row, item.hover, true)
                row,
                item.hover,
                true
             )


             for _, column in ipairs(NUMERIC_COLUMNS) do
             addCell(
                 local value = item[column.key]
                row,
                 item.slot,
                true
            )


                 addCell(row, value or '', false)
            for _, column in ipairs(
                NUMERIC_COLUMNS
            ) do
                 local value =
                    item[column.key]


                 if value then
                addNumericCell(
                    row,
                    value
                )
 
                 if value ~= nil then
                     totals[column.key] =
                     totals[column.key] =
                         totals[column.key] + value
                         totals[column.key] +
                        value
                 end
                 end
             end
             end


             addCell(row, item.effect, true)
            addNumericCell(
             addCell(row, item.droppedBy, true)
                row,
                item.haste,
                formatHaste(item.haste)
            )
 
            if item.haste ~= nil
                and (
                    bestHaste == nil
                    or item.haste > bestHaste
                )
            then
                bestHaste = item.haste
            end
 
            addNumericCell(
                row,
                item.weight,
                formatWeight(item.weight)
            )
 
            if item.weight ~= nil then
                totalWeight =
                    totalWeight +
                    item.weight
            end
 
             addCell(
                row,
                item.effect,
                true
            )
 
             addCell(
                row,
                item.droppedBy,
                true
            )
         end
         end
     end
     end
    --------------------------------------------------------------------
    -- Totals row
    --------------------------------------------------------------------


     local totalRow = output:tag('tr')
     local totalRow = output:tag('tr')
Line 429: Line 1,039:
         :css('font-weight', 'bold')
         :css('font-weight', 'bold')


     totalRow:tag('td')
     totalRow
        :tag('td')
         :attr('colspan', 2)
         :attr('colspan', 2)
         :css('text-align', 'right')
         :css('text-align', 'right')
         :wikitext('Totals')
         :wikitext('Totals')


     for _, column in ipairs(NUMERIC_COLUMNS) do
     for _, column in ipairs(
         addCell(
        NUMERIC_COLUMNS
    ) do
         addNumericCell(
             totalRow,
             totalRow,
             totals[column.key],
             totals[column.key]
            false
         )
         )
     end
     end
    local hasteCell =
        addNumericCell(
            totalRow,
            bestHaste,
            formatHaste(bestHaste)
        )
    hasteCell:attr(
        'title',
        'Highest haste value in the set; worn haste does not stack.'
    )
    addNumericCell(
        totalRow,
        totalWeight,
        formatWeight(totalWeight)
    )


     addCell(totalRow, '', false)
     addCell(totalRow, '', false)
Line 447: Line 1,077:
     return tostring(output)
     return tostring(output)
end
end
------------------------------------------------------------------------
-- Automatic category metadata
------------------------------------------------------------------------
local function splitMetadata(value)
    local values = {}
    for part in tostring(value or ''):gmatch(
        '[^,;]+'
    ) do
        part = trim(part)
        if part ~= '' then
            table.insert(values, part)
        end
    end
    return values
end
local function addCategory(
    categories,
    seen,
    categoryName
)
    categoryName = trim(categoryName)
    if categoryName == ''
        or seen[categoryName]
    then
        return
    end
    seen[categoryName] = true
    table.insert(
        categories,
        '[[Category:' ..
        categoryName ..
        ']]'
    )
end
local function addGearSetCategories(
    categories,
    seen,
    value
)
    for _, entry in ipairs(
        splitMetadata(value)
    ) do
        addCategory(
            categories,
            seen,
            entry .. ' Gear Sets'
        )
    end
end
local function buildCategories(args)
    local categories = {}
    local seen = {}
    addCategory(
        categories,
        seen,
        'Gear Sets'
    )
    local setType =
        trim(args.type):lower()
    if setType == 'weapon'
        or setType == 'weapons'
    then
        addCategory(
            categories,
            seen,
            'Weapon Sets'
        )
    else
        addCategory(
            categories,
            seen,
            'Armor Sets'
        )
    end
    addGearSetCategories(
        categories,
        seen,
        args.era
    )
    addGearSetCategories(
        categories,
        seen,
        args.source
    )
    addGearSetCategories(
        categories,
        seen,
        args.armor
    )
    addGearSetCategories(
        categories,
        seen,
        args.class
    )
    addGearSetCategories(
        categories,
        seen,
        args.region
    )
    addGearSetCategories(
        categories,
        seen,
        args.craft
    )
    addGearSetCategories(
        categories,
        seen,
        args.series
    )
    local cultures =
        splitMetadata(args.culture)
    if #cultures > 0 then
        addCategory(
            categories,
            seen,
            'Cultural Gear Sets'
        )
        for _, culture in ipairs(cultures) do
            addCategory(
                categories,
                seen,
                culture ..
                ' Cultural Gear Sets'
            )
        end
    end
    -- Allows unusual categories to be provided directly.
    for _, categoryName in ipairs(
        splitMetadata(args.categories)
    ) do
        addCategory(
            categories,
            seen,
            categoryName
        )
    end
    return table.concat(categories)
end
------------------------------------------------------------------------
-- Module entry point
------------------------------------------------------------------------


function p.main(frame)
function p.main(frame)
    -- The wrapper template does not need to forward every positional
    -- argument. Lua reads them directly from the template invocation.
     local parent = frame:getParent()
     local parent = frame:getParent()
     local args = parent and parent.args or frame.args
 
     local args =
        parent and parent.args
        or frame.args


     local indexedItems = {}
     local indexedItems = {}


     for argumentName, argumentValue in pairs(args) do
     for argumentName, argumentValue
         local numericIndex = tonumber(argumentName)
        in pairs(args)
         local itemName = trim(argumentValue)
    do
         local numericIndex =
            tonumber(argumentName)
 
         local itemName =
            trim(argumentValue)


         if numericIndex and itemName ~= '' then
         if numericIndex
            and itemName ~= ''
        then
             table.insert(
             table.insert(
                 indexedItems,
                 indexedItems,
Line 480: Line 1,286:
     local itemNames = {}
     local itemNames = {}


     for _, item in ipairs(indexedItems) do
     for _, item in ipairs(
         table.insert(itemNames, item.name)
        indexedItems
    ) do
         table.insert(
            itemNames,
            item.name
        )
     end
     end


     if #itemNames == 0 then
     if #itemNames == 0 then
         return '<strong class="error">' ..
         return
            '<strong class="error">' ..
             'Gear Set requires at least one item page.' ..
             'Gear Set requires at least one item page.' ..
             '</strong>'
             '</strong>'
     end
     end


     return renderTable(frame, args, itemNames)
     return
        renderTable(
            frame,
            args,
            itemNames
        ) ..
        buildCategories(args)
end
end


return p
return p

Revision as of 00:03, 14 July 2026

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

local p = {}

------------------------------------------------------------------------
-- Column configuration
------------------------------------------------------------------------

local NUMERIC_COLUMNS = {
    -- Combat vitality
    {
        key = 'ac',
        header = 'AC',
        labels = { 'AC' },
    },
    {
        key = 'hp',
        header = 'HP',
        labels = { 'HP' },
    },
    {
        key = 'mana',
        header = 'MANA',
        labels = { 'MANA' },
    },
    {
        key = 'endurance',
        header = 'END',
        labels = {
            'ENDURANCE',
            'ENDUR',
            'END',
        },
    },

    -- Base attributes
    {
        key = 'str',
        header = 'STR',
        labels = { 'STR' },
    },
    {
        key = 'sta',
        header = 'STA',
        labels = { 'STA' },
    },
    {
        key = 'int',
        header = 'INT',
        labels = { 'INT' },
    },
    {
        key = 'wis',
        header = 'WIS',
        labels = { 'WIS' },
    },
    {
        key = 'agi',
        header = 'AGI',
        labels = { 'AGI' },
    },
    {
        key = 'dex',
        header = 'DEX',
        labels = { 'DEX' },
    },
    {
        key = 'cha',
        header = 'CHA',
        labels = { 'CHA' },
    },

    -- Resistances
    {
        key = 'mr',
        header = 'MR',
        labels = {
            'SV MAGIC',
            'SV MAG',
            'MR',
        },
    },
    {
        key = 'fr',
        header = 'FR',
        labels = {
            'SV FIRE',
            'FR',
        },
    },
    {
        key = 'cr',
        header = 'CR',
        labels = {
            'SV COLD',
            'CR',
        },
    },
    {
        key = 'dr',
        header = 'DR',
        labels = {
            'SV DISEASE',
            'SV DIS',
            'DR',
        },
    },
    {
        key = 'pr',
        header = 'PR',
        labels = {
            'SV POISON',
            'SV POI',
            'PR',
        },
    },
    {
        key = 'vr',
        header = 'VR',
        labels = {
            'SV VR',
            'VR',
        },
    },
}

local TOTAL_COLUMN_COUNT =
    2 +                  -- Item and Slot
    #NUMERIC_COLUMNS +
    4                    -- Haste, Weight, Effect, Dropped By

------------------------------------------------------------------------
-- General helpers
------------------------------------------------------------------------

local function trim(value)
    return mw.text.trim(tostring(value or ''))
end

local function escapePattern(value)
    return (
        tostring(value or ''):gsub(
            '([%^%$%(%)%%%.%[%]%*%+%-%?])',
            '%%%1'
        )
    )
end

local function formatPlainNumber(value)
    if value == nil then
        return ''
    end

    if math.floor(value) == value then
        return tostring(math.floor(value))
    end

    local formatted = string.format('%.2f', value)

    formatted = formatted:gsub('0+$', '')
    formatted = formatted:gsub('%.$', '')

    return formatted
end

local function formatHaste(value)
    if value == nil then
        return ''
    end

    local formatted = formatPlainNumber(value)

    if value > 0 then
        return '+' .. formatted .. '%'
    end

    return formatted .. '%'
end

local function formatWeight(value)
    if value == nil then
        return ''
    end

    local formatted = string.format('%.2f', value)

    formatted = formatted:gsub('0+$', '')
    formatted = formatted:gsub('%.$', '')

    -- Preserve the familiar EverQuest weight style:
    -- 2 becomes 2.0, while 0.1 remains 0.1.
    if not formatted:find('%.', 1, true) then
        formatted = formatted .. '.0'
    end

    return formatted
end

------------------------------------------------------------------------
-- Itempage template parser
------------------------------------------------------------------------

-- Reads the named arguments inside the first {{Itempage ...}} invocation.
--
-- This parser keeps track of nested templates, wiki links, and wiki tables,
-- preventing internal pipes from being mistaken for Itempage parameters.
local function parseItempageParameters(content)
    local startPosition =
        content:find('{{%s*[Ii]tempage[%s|]')

    if not startPosition then
        return nil
    end

    local segments = {}
    local buffer = {}

    local curlyDepth = 1
    local squareDepth = 0
    local tableDepth = 0

    local position = startPosition + 2
    local contentLength = #content

    while position <= contentLength do
        local pair =
            content:sub(position, position + 1)

        local character =
            content:sub(position, position)

        if pair == '{{' then
            curlyDepth = curlyDepth + 1

            table.insert(buffer, pair)

            position = position + 2

        elseif pair == '}}' then
            if curlyDepth == 1 then
                table.insert(
                    segments,
                    table.concat(buffer)
                )

                break
            end

            curlyDepth = curlyDepth - 1

            table.insert(buffer, pair)

            position = position + 2

        elseif pair == '[[' then
            squareDepth = squareDepth + 1

            table.insert(buffer, pair)

            position = position + 2

        elseif pair == ']]' and squareDepth > 0 then
            squareDepth = squareDepth - 1

            table.insert(buffer, pair)

            position = position + 2

        elseif pair == '{|' then
            tableDepth = tableDepth + 1

            table.insert(buffer, pair)

            position = position + 2

        elseif pair == '|}' and tableDepth > 0 then
            tableDepth = tableDepth - 1

            table.insert(buffer, pair)

            position = position + 2

        elseif character == '|'
            and curlyDepth == 1
            and squareDepth == 0
            and tableDepth == 0
        then
            table.insert(
                segments,
                table.concat(buffer)
            )

            buffer = {}

            position = position + 1

        else
            table.insert(buffer, character)

            position = position + 1
        end
    end

    if #segments < 2 then
        return nil
    end

    local parameters = {}

    -- Segment 1 contains the template name.
    for index = 2, #segments do
        local parameterName, parameterValue =
            segments[index]:match(
                '^%s*([%w_%-]+)%s*=(.*)$'
            )

        if parameterName then
            parameters[parameterName:lower()] =
                trim(parameterValue)
        end
    end

    return parameters
end

------------------------------------------------------------------------
-- Page loading
------------------------------------------------------------------------

local function getPageContent(pageName)
    local title = mw.title.new(pageName)

    -- Follow ordinary redirects.
    for _ = 1, 4 do
        if not title then
            return nil
        end

        local content = title:getContent()

        if not content then
            return nil
        end

        local redirectTarget =
            content:match(
                '^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]' ..
                '%s*%[%[([^%]|#]+)'
            )

        if not redirectTarget then
            return content
        end

        title = mw.title.new(
            trim(redirectTarget)
        )
    end

    return nil
end

------------------------------------------------------------------------
-- Statsblock parsing
------------------------------------------------------------------------

local function normalizeStatsblock(statsblock)
    local stats = tostring(statsblock or '')

    stats = stats:gsub('\r\n', '\n')
    stats = stats:gsub('\r', '\n')

    -- Remove comments.
    stats = stats:gsub('<!%-%-.-%-%->', '')

    -- Convert every form of <br> into a real line ending.
    stats = stats:gsub(
        '<[bB][rR]%s*/?%s*>',
        '\n'
    )

    stats = stats:gsub('&nbsp;', ' ')
    stats = stats:gsub('[ \t]+\n', '\n')

    return stats
end

local function extractNumericValue(
    statsblock,
    labels,
    allowDecimal
)
    local uppercaseStats =
        tostring(statsblock or ''):upper()

    local valuePattern

    if allowDecimal then
        valuePattern =
            '([%+%-]?%d+%.?%d*)'
    else
        valuePattern =
            '([%+%-]?%d+)'
    end

    for _, label in ipairs(labels) do
        local pattern =
            escapePattern(label:upper()) ..
            '%s*:%s*' ..
            valuePattern

        local value =
            uppercaseStats:match(pattern)

        if value then
            return tonumber(value)
        end
    end

    return nil
end

-- Returns every line value matching one of the supplied labels.
--
-- Example:
-- Effect: [[Swift Spirit]] (Worn)
--
-- returns:
-- [[Swift Spirit]] (Worn)
local function extractLabeledLines(
    statsblock,
    labels
)
    local results = {}
    local seen = {}

    for line in tostring(statsblock or ''):gmatch('[^\n]+') do
        local cleanLine = trim(line)
        local uppercaseLine = cleanLine:upper()

        for _, label in ipairs(labels) do
            local pattern =
                '^' ..
                escapePattern(label:upper()) ..
                '%s*:%s*'

            local _, valueStart =
                uppercaseLine:find(pattern)

            if valueStart then
                local value =
                    trim(
                        cleanLine:sub(
                            valueStart + 1
                        )
                    )

                if value ~= ''
                    and not seen[value]
                then
                    seen[value] = true

                    table.insert(
                        results,
                        value
                    )
                end

                break
            end
        end
    end

    return results
end

local function extractLine(statsblock, labels)
    local values =
        extractLabeledLines(
            statsblock,
            labels
        )

    return values[1] or ''
end

------------------------------------------------------------------------
-- Effects
------------------------------------------------------------------------

local function buildEffect(
    parameters,
    statsblock
)
    local results = {}
    local seen = {}

    local function addEffect(value)
        value = trim(value)

        if value == ''
            or seen[value]
        then
            return
        end

        seen[value] = true

        table.insert(results, value)
    end

    --------------------------------------------------------------------
    -- Explicit statsblock effects
    --------------------------------------------------------------------

    local explicitEffects =
        extractLabeledLines(
            statsblock,
            {
                'Effect',
                'Click Effect',
                'Worn Effect',
                'Proc Effect',
                'Combat Effect',
            }
        )

    for _, effect in ipairs(explicitEffects) do
        addEffect(effect)
    end

    --------------------------------------------------------------------
    -- Focus effect parameter
    --------------------------------------------------------------------

    local focusEffect =
        trim(parameters.focus_effect)

    if focusEffect ~= '' then
        if focusEffect:find('%[%[') then
            addEffect(
                'Focus: ' .. focusEffect
            )
        else
            addEffect(
                'Focus: [[' ..
                focusEffect ..
                ']]'
            )
        end
    end

    --------------------------------------------------------------------
    -- Passive regeneration effects
    --------------------------------------------------------------------

    local passiveEffectLabels = {
        'HP Regen',
        'Mana Regen',
        'Endurance Regen',
    }

    for _, label in ipairs(
        passiveEffectLabels
    ) do
        local values =
            extractLabeledLines(
                statsblock,
                { label }
            )

        for _, value in ipairs(values) do
            addEffect(
                label .. ': ' .. value
            )
        end
    end

    return table.concat(results, '<br>')
end

------------------------------------------------------------------------
-- Drop-source extraction
------------------------------------------------------------------------

local function extractDropMobs(dropsfrom)
    local drops =
        tostring(dropsfrom or '')

    drops = drops:gsub('\r\n', '\n')
    drops = drops:gsub('\r', '\n')
    drops = drops:gsub('<!%-%-.-%-%->', '')

    local results = {}
    local seen = {}

    for line in drops:gmatch('[^\n]+') do
        local mob =
            line:match(
                '^%s*%*+%s*(.-)%s*$'
            )

        if mob
            and mob ~= ''
            and not seen[mob]
        then
            seen[mob] = true

            table.insert(results, mob)
        end
    end

    return table.concat(results, '<br>')
end

------------------------------------------------------------------------
-- Item rendering and loading
------------------------------------------------------------------------

local function createHoverLink(
    frame,
    pageName
)
    local success, rendered =
        pcall(
            function()
                return frame:preprocess(
                    '{{:' .. pageName .. '}}'
                )
            end
        )

    if success
        and trim(rendered) ~= ''
    then
        return rendered
    end

    return '[[' .. pageName .. ']]'
end

local function readItem(
    frame,
    pageName
)
    local content =
        getPageContent(pageName)

    if not content then
        return nil,
            'Item page does not exist or could not be read.'
    end

    local parameters =
        parseItempageParameters(content)

    if not parameters then
        return nil,
            'No Itempage template was found on the item page.'
    end

    local statsblock =
        normalizeStatsblock(
            parameters.statsblock
        )

    if statsblock == '' then
        return nil,
            'The item has no statsblock.'
    end

    local item = {
        pageName = pageName,

        itemName =
            trim(parameters.itemname) ~= ''
            and trim(parameters.itemname)
            or pageName,

        hover =
            createHoverLink(
                frame,
                pageName
            ),

        slot =
            extractLine(
                statsblock,
                { 'Slot' }
            ),

        haste =
            extractNumericValue(
                statsblock,
                { 'Haste' },
                true
            ),

        weight =
            extractNumericValue(
                statsblock,
                {
                    'WT',
                    'Weight',
                },
                true
            ),

        effect =
            buildEffect(
                parameters,
                statsblock
            ),

        droppedBy =
            extractDropMobs(
                parameters.dropsfrom
            ),
    }

    for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
        item[column.key] =
            extractNumericValue(
                statsblock,
                column.labels,
                false
            )
    end

    return item
end

------------------------------------------------------------------------
-- HTML table helpers
------------------------------------------------------------------------

local function addCell(
    row,
    value,
    alignLeft
)
    local cell = row:tag('td')

    if alignLeft then
        cell:css(
            'text-align',
            'left'
        )
    end

    if value ~= nil
        and value ~= ''
    then
        cell:wikitext(
            tostring(value)
        )
    end

    return cell
end

local function addNumericCell(
    row,
    numericValue,
    displayedValue
)
    local cell = row:tag('td')

    if numericValue ~= nil then
        cell:attr(
            'data-sort-value',
            tostring(numericValue)
        )

        cell:wikitext(
            displayedValue
                or formatPlainNumber(
                    numericValue
                )
        )
    end

    return cell
end

local function addHeader(
    row,
    text,
    colspan
)
    local header = row:tag('th')

    header:attr(
        'scope',
        colspan and 'colgroup' or 'col'
    )

    if colspan then
        header:attr(
            'colspan',
            colspan
        )
    end

    header:wikitext(text)

    return header
end

------------------------------------------------------------------------
-- Table rendering
------------------------------------------------------------------------

local function renderTable(
    frame,
    args,
    itemNames
)
    local output =
        mw.html.create('table')

    output
        :addClass('wikitable')
        :addClass('sortable')
        :addClass('eql-gear-set-table')
        :css('text-align', 'center')

    --------------------------------------------------------------------
    -- Caption
    --------------------------------------------------------------------

    local caption = trim(args.caption)

    if caption == '' then
        caption = trim(args.name)
    end

    if caption == '' then
        caption =
            mw.title.getCurrentTitle().text
    end

    output
        :tag('caption')
        :wikitext(caption)

    --------------------------------------------------------------------
    -- Group headings
    --------------------------------------------------------------------

    local groupRow = output:tag('tr')

    groupRow
        :addClass('sortbottom')
        :css('font-weight', 'bold')

    addHeader(
        groupRow,
        'Item Info',
        2
    )

    addHeader(
        groupRow,
        'Combat Vitality',
        4
    )

    addHeader(
        groupRow,
        'Base Attributes',
        7
    )

    addHeader(
        groupRow,
        'Resistances',
        6
    )

    addHeader(
        groupRow,
        'Miscellaneous',
        4
    )

    --------------------------------------------------------------------
    -- Column headings
    --------------------------------------------------------------------

    local headerRow = output:tag('tr')

    addHeader(headerRow, 'Item')
    addHeader(headerRow, 'Slot')

    for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
        addHeader(
            headerRow,
            column.header
        )
    end

    addHeader(headerRow, 'Haste')
    addHeader(headerRow, 'Weight')
    addHeader(headerRow, 'Effect')
    addHeader(headerRow, 'Dropped By')

    --------------------------------------------------------------------
    -- Totals
    --------------------------------------------------------------------

    local totals = {}

    for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
        totals[column.key] = 0
    end

    local totalWeight = 0
    local bestHaste = nil

    --------------------------------------------------------------------
    -- Item rows
    --------------------------------------------------------------------

    for _, pageName in ipairs(itemNames) do
        local item, errorMessage =
            readItem(
                frame,
                pageName
            )

        if not item then
            local errorRow =
                output:tag('tr')

            errorRow
                :tag('td')
                :attr(
                    'colspan',
                    TOTAL_COLUMN_COUNT
                )
                :addClass('error')
                :css(
                    'text-align',
                    'left'
                )
                :wikitext(
                    '[[' ..
                    pageName ..
                    ']]: ' ..
                    errorMessage
                )
        else
            local row = output:tag('tr')

            addCell(
                row,
                item.hover,
                true
            )

            addCell(
                row,
                item.slot,
                true
            )

            for _, column in ipairs(
                NUMERIC_COLUMNS
            ) do
                local value =
                    item[column.key]

                addNumericCell(
                    row,
                    value
                )

                if value ~= nil then
                    totals[column.key] =
                        totals[column.key] +
                        value
                end
            end

            addNumericCell(
                row,
                item.haste,
                formatHaste(item.haste)
            )

            if item.haste ~= nil
                and (
                    bestHaste == nil
                    or item.haste > bestHaste
                )
            then
                bestHaste = item.haste
            end

            addNumericCell(
                row,
                item.weight,
                formatWeight(item.weight)
            )

            if item.weight ~= nil then
                totalWeight =
                    totalWeight +
                    item.weight
            end

            addCell(
                row,
                item.effect,
                true
            )

            addCell(
                row,
                item.droppedBy,
                true
            )
        end
    end

    --------------------------------------------------------------------
    -- Totals row
    --------------------------------------------------------------------

    local totalRow = output:tag('tr')

    totalRow
        :addClass('sortbottom')
        :css('font-weight', 'bold')

    totalRow
        :tag('td')
        :attr('colspan', 2)
        :css('text-align', 'right')
        :wikitext('Totals')

    for _, column in ipairs(
        NUMERIC_COLUMNS
    ) do
        addNumericCell(
            totalRow,
            totals[column.key]
        )
    end

    local hasteCell =
        addNumericCell(
            totalRow,
            bestHaste,
            formatHaste(bestHaste)
        )

    hasteCell:attr(
        'title',
        'Highest haste value in the set; worn haste does not stack.'
    )

    addNumericCell(
        totalRow,
        totalWeight,
        formatWeight(totalWeight)
    )

    addCell(totalRow, '', false)
    addCell(totalRow, '', false)

    return tostring(output)
end

------------------------------------------------------------------------
-- Automatic category metadata
------------------------------------------------------------------------

local function splitMetadata(value)
    local values = {}

    for part in tostring(value or ''):gmatch(
        '[^,;]+'
    ) do
        part = trim(part)

        if part ~= '' then
            table.insert(values, part)
        end
    end

    return values
end

local function addCategory(
    categories,
    seen,
    categoryName
)
    categoryName = trim(categoryName)

    if categoryName == ''
        or seen[categoryName]
    then
        return
    end

    seen[categoryName] = true

    table.insert(
        categories,
        '[[Category:' ..
        categoryName ..
        ']]'
    )
end

local function addGearSetCategories(
    categories,
    seen,
    value
)
    for _, entry in ipairs(
        splitMetadata(value)
    ) do
        addCategory(
            categories,
            seen,
            entry .. ' Gear Sets'
        )
    end
end

local function buildCategories(args)
    local categories = {}
    local seen = {}

    addCategory(
        categories,
        seen,
        'Gear Sets'
    )

    local setType =
        trim(args.type):lower()

    if setType == 'weapon'
        or setType == 'weapons'
    then
        addCategory(
            categories,
            seen,
            'Weapon Sets'
        )
    else
        addCategory(
            categories,
            seen,
            'Armor Sets'
        )
    end

    addGearSetCategories(
        categories,
        seen,
        args.era
    )

    addGearSetCategories(
        categories,
        seen,
        args.source
    )

    addGearSetCategories(
        categories,
        seen,
        args.armor
    )

    addGearSetCategories(
        categories,
        seen,
        args.class
    )

    addGearSetCategories(
        categories,
        seen,
        args.region
    )

    addGearSetCategories(
        categories,
        seen,
        args.craft
    )

    addGearSetCategories(
        categories,
        seen,
        args.series
    )

    local cultures =
        splitMetadata(args.culture)

    if #cultures > 0 then
        addCategory(
            categories,
            seen,
            'Cultural Gear Sets'
        )

        for _, culture in ipairs(cultures) do
            addCategory(
                categories,
                seen,
                culture ..
                ' Cultural Gear Sets'
            )
        end
    end

    -- Allows unusual categories to be provided directly.
    for _, categoryName in ipairs(
        splitMetadata(args.categories)
    ) do
        addCategory(
            categories,
            seen,
            categoryName
        )
    end

    return table.concat(categories)
end

------------------------------------------------------------------------
-- Module entry point
------------------------------------------------------------------------

function p.main(frame)
    local parent = frame:getParent()

    local args =
        parent and parent.args
        or frame.args

    local indexedItems = {}

    for argumentName, argumentValue
        in pairs(args)
    do
        local numericIndex =
            tonumber(argumentName)

        local itemName =
            trim(argumentValue)

        if numericIndex
            and itemName ~= ''
        then
            table.insert(
                indexedItems,
                {
                    index = numericIndex,
                    name = itemName,
                }
            )
        end
    end

    table.sort(
        indexedItems,
        function(left, right)
            return left.index < right.index
        end
    )

    local itemNames = {}

    for _, item in ipairs(
        indexedItems
    ) do
        table.insert(
            itemNames,
            item.name
        )
    end

    if #itemNames == 0 then
        return
            '<strong class="error">' ..
            'Gear Set requires at least one item page.' ..
            '</strong>'
    end

    return
        renderTable(
            frame,
            args,
            itemNames
        ) ..
        buildCategories(args)
end

return p