跳转到内容

模組:Random list

本页使用了标题或全文手工转换
维基百科,自由的百科全书

local p = {}

-- 解析 wiki 列表(* 每行)
local function parse_wikilines(text)
    local items = {}
    for _, line in ipairs(mw.text.split(text, '\n')) do
        line = mw.text.trim(line)
        line = line:gsub('^%*%s*', '')
        if line ~= '' then
            table.insert(items, line)
        end
    end
    return items
end

-- 解析自訂分隔符(Lua pattern)
local function parse_by_separator(text, sep)
    local items = {}
    for _, part in ipairs(mw.text.split(text, sep)) do
        part = mw.text.trim(part)
        if part ~= '' then
            table.insert(items, part)
        end
    end
    return items
end

function p.randitems(frame)
    -- 1. 參數
    local text  = frame.args[1] or ''
    local count = tonumber(frame.args.count) or 1
    local sep   = frame.args[2]

    -- 2. 解析列表
    local items
    if sep and sep ~= '' then
        -- 自訂分隔符模式
        items = parse_by_separator(text, sep)
    else
        -- wiki 列表模式
        items = parse_wikilines(text)
    end

    local n = #items
    if n == 0 then return '' end

    if count < 1 then count = 1 end
    if count > n then count = n end

    -- 3. 隨機洗牌(頁面穩定)
    local seed = tonumber(mw.hash.hashValue(
        'md5',
        mw.title.getCurrentTitle().prefixedText
    ):sub(1, 8), 16)

    math.randomseed(seed + os.clock() * 100000)

    for i = n, 2, -1 do
        local j = math.random(i)
        items[i], items[j] = items[j], items[i]
    end

    -- 4. 輸出
    local result = {}
    for i = 1, count do
        result[#result + 1] = '* ' .. items[i]
    end

    return table.concat(result, '\n')
end

return p