Module:RandomItemSequence: Difference between revisions

No edit summary
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}
local Random = require('Module:Random')
local Random = require('Module:Random')
-- Seed once per page parse
Random.seed(os.time())


-- Fisher–Yates shuffle
-- Fisher–Yates shuffle
Line 13: Line 10:
end
end


-- render function
function p.render(frame)
function p.render(frame)
     local args = frame:getParent().args
     local args = frame:getParent().args
Line 19: Line 15:
     local tooltip = args.tooltip or ""
     local tooltip = args.tooltip or ""
     local link = args.link 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 = {}
     local items = {}
     for item in string.gmatch(itemsParam, '([^;]+)') do
     for item in string.gmatch(itemsParam, '([^;]+)') do
         item = item:gsub("^%s*(.-)%s*$", "%1")
         item = item:gsub("^%s*(.-)%s*$", "%1") -- trim spaces
         table.insert(items, item)
         table.insert(items, item)
     end
     end
Line 31: Line 33:


     shuffle(items)
     shuffle(items)
    -- Generate a dummy unique value to force MediaWiki to treat each template expansion as distinct
    local unique = tostring(os.clock() + Random.random(1e6))


     return frame:expandTemplate{
     return frame:expandTemplate{
Line 40: Line 39:
             item = table.concat(items, "; "),
             item = table.concat(items, "; "),
             tooltip = tooltip,
             tooltip = tooltip,
             link = link,
             link = link
            _dummy = unique  -- ignored by ItemSlot, only for cache-busting
         }
         }
     }
     }

Latest revision as of 19:01, 28 December 2025

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