Module:Chapters

From Candypedia
Revision as of 08:17, 19 May 2024 by SuitCase (talk | contribs)

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

-- Module:Chapters
local p = {}

function p.getChapterList()
    local listPage = mw.title.new('Template:ChapterList')
    if not listPage then
        return {}
    end

    local content = listPage:getContent()
    if not content then
        return {}
    end

    local chapters = {}
    for number, title, date, pagecount in string.gmatch(content, "{{Chapter|number=(%d+)|title=([^|]+)|date=([^|]+)|pagecount=(%d+)}}") do
        table.insert(chapters, {number = tonumber(number), title = title, date = date, pagecount = tonumber(pagecount)})
    end

    return chapters
end

function p.getChapterDetails(chapterTitle, detail)
    local chapters = p.getChapterList()
    for _, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle then
            return chapter[detail]
        end
    end
    return nil
end

function p.getTotalChapters()
    return #p.getChapterList()
end

function p.getNextChapter(chapterTitle)
    local chapters = p.getChapterList()
    for i, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle and i < #chapters then
            return chapters[i + 1].title
        end
    end
    return nil
end

function p.getPreviousChapter(chapterTitle)
    local chapters = p.getChapterList()
    for i, chapter in ipairs(chapters) do
        if chapter.title == chapterTitle and i > 1 then
            return chapters[i - 1].title
        end
    end
    return nil
end

return p