Permanently protected module

Module:Did you know

From MicroWiki, the free micronational encyclopædia
Jump to navigation Jump to search
local p = {}

local function tableToWikiText(t)
    local text = ""
    for _, v in ipairs(t) do
        text = text .. "* … that " .. tostring(v) .. "\n"
    end
    return text
end

function p.getRandomEntries()

    local title = mw.title.new("MicroWiki:Did you know/Entries")
    if not title then return nil end
    local content = title:getContent()
    if not content then return nil end

	-- Store all of the lines in the document
    local entries = {}
    local lines = mw.text.split(content, '\n')
    for i, line in ipairs(lines) do
        local entry = line:match("^%*(.+)$")
        if entry then
            table.insert(entries, entry)
        end
    end
    if #entries == 0 then return nil end

    -- Shuffle the entries and select up to 5 random ones
    math.randomseed(os.time())
    local randomEntries = {}
    for i = 1, math.min(5, #entries) do
        local index = math.random(#entries)
        table.insert(randomEntries, entries[index])
        table.remove(entries, index)
    end

    return tableToWikiText(randomEntries)
end

return p