Module:RandomTableRow

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

local p = {}

--[[
My old code incase the table one for some reason breaks, will need adjusting as it's wrong and not generic but hey ho, it's here if we need it.

local data = mw.loadJsonData( 'Module:RandomTip/data.json' )

local function getTipsCount()
	local tips_count = 0
	for key,value in pairs(data.tips) do 
		tips_count = tips_count + 1
	end	
	return tips_count
end

function p.getRandomDailyTip()
    local seed = os.date("%Y%m%d")
    math.randomseed(tonumber(seed))
    
    local tips_count = getTipsCount()
	local index = math.random(1, tips_count)
   
	return data.tips[index]
end

function p.createTable() 
	local table_index = 0
	local tbl = mw.html.create('table'):addClass("wikitable")
	tbl:tag('tr')
		:tag('th'):wikitext("ID"):done()
		:tag('th'):wikitext("Tip"):done()
	:done()
	for k, v in pairs(data.tips) do
		table_index = table_index + 1
		tbl:tag('tr')
			:tag('td')
				:wikitext(table_index)
			:tag('td')
				:wikitext(v)
	end
	return tostring(tbl)
end--]]

--Makes a seed based on the date so that it always returns the same first random number in sequence which changes every day
local function getDailyRandomNumber(maxNum) 
   local seed = os.date("%Y%m%d")
   math.randomseed(tonumber(seed))
   return math.random(1, maxNum)
end

--Gets page content (kinda self-explanatory imo)
local function getPageContent(page)
	local title = mw.title.new(page)
	if not title then return nil end
	return title:getContent()
end

--Parses the page which contains the table so it only grabs the strings which doesn't include the ID column as it ignores |{number}
local function parseTableContent(content)
	local rows  = {}
	for line in content:gmatch("[^\r\n]+") do
        if line:match("^|%-$") then
            inRow = true
            row = nil
        elseif inRow then
        	if not line:match("^|(%d+)$") then
	            row = line:match("^|(.+)$")
	            if row then
	                table.insert(rows, row)
	                inRow = false
	            end
	    	end
        end
	end
	return rows
end

--Main function to call the local functions and return errors if needs be
function p.main(frame)
	local rows = {}
	local page = frame.args[1]
	local content = getPageContent(page)
	if not content then return 'Page not found' end
	
	local rows = parseTableContent(content)
	if(#rows == 0) then return 'No rows found' end
    
    local index = getDailyRandomNumber(#rows)
	return rows[index]
end

return p
Cookies help us deliver our services. By using our services, you agree to our use of cookies.