Module:RandomItemSequence

Revision as of 19:01, 28 December 2025 by Faintfulness (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local p = {}
local Random = require('Module:Random')

-- Fisher–Yates shuffle
local function shuffle(t)
    for i = #t, 2, -1 do
        local j = Random.random(i)
        t[i], t[j] = t[j], t[i]
    end
end

function p.render(frame)
    local args = frame:getParent().args
    local itemsParam = args.items or ""
    local tooltip = args.tooltip or ""
    local link = args.link or ""

    -- Only reseed if the editor provided a valid numeric seed
    local seed = tonumber(args.reseed)
    if seed then
        Random.seed(seed)
    end

    local items = {}
    for item in string.gmatch(itemsParam, '([^;]+)') do
        item = item:gsub("^%s*(.-)%s*$", "%1") -- trim spaces
        table.insert(items, item)
    end

    if #items == 0 then
        return ""
    end

    shuffle(items)

    return frame:expandTemplate{
        title = "ItemSlot",
        args = {
            item = table.concat(items, "; "),
            tooltip = tooltip,
            link = link
        }
    }
end

return p