Module:Did you know

Documentation for this module may be created at Module:Did you know/doc

-- implements [[Template:Did you know]]

local p = { }

local function get_facts_from(title)
	frame = mw.getCurrentFrame()

	str = frame:expandTemplate{title = title}
	facts = {}
	for s in str:gmatch("[^\r\n]+") do
	    table.insert(facts, s)
	end
	
	return facts
end

local function pick_facts(all_facts, n)
	facts = {}

	repeat
		i = math.random(1, #all_facts)
		if facts[i] == nil then
			facts[i] = all_facts[i]
			n = n - 1
		end
	until n == 0

	return facts
end

function p.facts(frame)
	date = os.date("*t")
	math.randomseed(date.year * date.month * date.day)

	all_facts = get_facts_from("Did you know/Facts")
	facts = pick_facts(all_facts, frame.args[1] or 6)
	
	result = ""
	for _, v in pairs(facts) do
		result = result .. v .. "\n"
	end
	
	return result
end

return p