Module:RecursiveSelectiveList

Revision as of 06:30, 22 December 2024 by EnWikiAdmin (talk | contribs) (Created page with "local p = {} local function getPagesFromCategory(categoryName, limit, visitedCategories, pages) local categoryTitle = mw.title.new("Category:" .. categoryName) if not categoryTitle or not categoryTitle.exists then return pages -- Return the list if the category doesn't exist end -- Prevent infinite loops in case of circular category references if visitedCategories[categoryName] then return pages end visitedCategories[category...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local p = {}

local function getPagesFromCategory(categoryName, limit, visitedCategories, pages)
    local categoryTitle = mw.title.new("Category:" .. categoryName)
    if not categoryTitle or not categoryTitle.exists then
        return pages -- Return the list if the category doesn't exist
    end

    -- Prevent infinite loops in case of circular category references
    if visitedCategories[categoryName] then
        return pages
    end
    visitedCategories[categoryName] = true

    -- Get all members of the category
    local members = categoryTitle:linkedPages()
    for _, member in ipairs(members) do
        if member.namespace == 0 then -- Only include Main namespace pages
            table.insert(pages, member)
        elseif member.namespace == 14 then -- If it's a subcategory
            getPagesFromCategory(member.text, limit, visitedCategories, pages)
        end

        -- Stop if we've reached the limit
        if limit and #pages >= limit then
            return pages
        end
    end

    return pages
end

function p.main(frame)
    local args = frame:getParent().args
    local categoryName = args["categoryName"]
    local limit = tonumber(args["limit"])

    if not categoryName then
        return "Error: Please provide a category name."
    end

    local pages = getPagesFromCategory(categoryName, limit, {}, {})
    if #pages == 0 then
        return "No pages found."
    end

    -- Generate a bulleted list
    local output = {}
    for _, page in ipairs(pages) do
        table.insert(output, "* [[" .. page.prefixedText .. "]]")
    end

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

return p