Jump to content

Module:Table row counter

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 09:35, 21 June 2014 (add missing function parameter). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- This module counts table rows in wikitext.

local p = {}

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {parentOnly = true})
	local tableNo = tonumber(args[1])
	local ignoreRows = tonumber(args.ignore)
	local page = args.page
	local success, titleObj = pcall(mw.title.new, page)
	if not success then
		titleObj = nil
	end
	return p.luaMain(tableNo, ignoreRows, titleObj) or ''
end

function p.luaMain(tableNo, ignoreRows, titleObj)
	titleObj = titleObj or mw.title.getCurrentTitle()

	-- Get the page content.
	local content = titleObj:getContent()
	if not content then
		return nil
	end

	-- Find the wikitables on that page.
	local wikitables = {}
	do
		local iWikitable = 0
		for s in content:gmatch('\n({|.-\n|})') do
			iWikitable = iWikitable + 1
			wikitables[iWikitable] = s
		end
	end

	-- Find the wikitable to work on.
	tableNo = tableNo or 1
	local wikitable = wikitables[tableNo]
	if not wikitable then
		return nil
	end

	-- Count the number of rows.
	local count
	do
		local temp
		temp, count = wikitable:gsub('\n|%-', '\n|-')
	end

	-- Control for missing row markers at the start.
	if not wikitable:match('^{|[^\n]-%s*\n|-') then
		count = count + 1
	end

	-- Control for extra row markers at the end.
	if wikitable:find('\n|%-[^\n]-%s*\n|}$') then
		count = count - 1
	end

	-- Subtract the number of rows to ignore, and make sure the result isn't below zero.
	ignoreRows = ignoreRows or 0
	count = count - ignoreRows
	if count < 0 then
		count = 0
	end
	return count
end

return p