跳转到内容

模块:Test:修订间差异

来自LabAnimalWiki
Czhen留言 | 贡献
无编辑摘要
Czhen留言 | 贡献
无编辑摘要
第8行: 第8行:
     -- 使用DPL调用获取分类下的页面列表
     -- 使用DPL调用获取分类下的页面列表
     -- 注意:DPL的调用方式可能因版本和配置而异,以下是一种常见方式
     -- 注意:DPL的调用方式可能因版本和配置而异,以下是一种常见方式
     local dpl_output = mw.ext.dpl.dump({
     local dpl_output = mw.ext.dlp.dump({
         category = category,
         category = category,
         notcategory = args['notcategory'], -- 可选:排除的分类
         notcategory = args['notcategory'], -- 可选:排除的分类

2025年9月8日 (一) 10:14的版本

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

local p = {} -- 初始化模块对象

function p.getRandomPages(frame)
    local args = frame.args
    local category = args['category'] or '分类名称' -- 默认分类名称,最好从参数传入
    local count = tonumber(args['count']) or 5 -- 默认显示5条,最好从参数传入

    -- 使用DPL调用获取分类下的页面列表
    -- 注意:DPL的调用方式可能因版本和配置而异,以下是一种常见方式
    local dpl_output = mw.ext.dlp.dump({
        category = category,
        notcategory = args['notcategory'], -- 可选:排除的分类
        namespace = args['namespace'] or '0', -- 可选:名字空间,默认为主名字空间(0)
        ordermethod = 'title', -- 初始排序方式,后续会随机化
        mode = 'unordered',
        ignoreerrors = true, -- 忽略错误
        -- 为了性能,初次获取可以限制一个较大的数量,然后从中随机选择
        count = 50 -- 假设我们从分类中最多取50页再进行随机选择
    })

    -- 检查DPL是否返回了结果
    if type(dpl_output) ~= 'table' or #dpl_output == 0 then
        return "''该分类下暂无页面或获取页面时出错。''"
    end

    -- 将DPL输出中的页面标题提取到一个新表中
    local pages = {}
    for _, page in ipairs(dpl_output) do
        table.insert(pages, page.title)
    end

    -- 随机化页面列表
    math.randomseed(os.time()) -- 设置随机种子,增加随机性
    for i = #pages, 2, -1 do
        local j = math.random(i)
        pages[i], pages[j] = pages[j], pages[i] -- 交换元素(Fisher-Yates洗牌算法)
    end

    -- 只取前`count`个结果
    local selected_pages = {}
    for i = 1, math.min(count, #pages) do
        table.insert(selected_pages, pages[i])
    end

    -- 格式化输出为Wiki文本列表
    local output = {}
    for _, title in ipairs(selected_pages) do
        -- 创建页面链接
        table.insert(output, '* [[' .. title .. ']]')
    end

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

return p