Module:Table row counter

-- This module is ported from dev.fandom.com -- Please use SPACES for indentation

-- This module counts table rows in wikitext. -- Syntax: -- local p = {} local getArgs = require('Module:Arguments').getArgs

function p.isCurrentPage(pageTitle) return (not pageTitle) or pageTitle == "" or mw.title.getCurrentTitle == pageTitle end

function p.getTitleObj(pageTitle) local titleObj -- No need for expensive function when using current page if p.isCurrentPage(pageTitle) then titleObj = mw.title.getCurrentTitle else _, titleObj = pcall(mw.title.new, pageTitle) end return titleObj end

function p.getAllTables(content) local wikitables = {} local iWikitable = 0 local s1 = content:match('^({|.-\n|})') if s1 then iWikitable = iWikitable + 1 wikitables[iWikitable] = s1   end for s in content:gmatch('\n({|.-\n|})') do       iWikitable = iWikitable + 1 wikitables[iWikitable] = s   end return wikitables end

function p.getTableById(wikitables, theId) for i, s in ipairs(wikitables) do       local arguments = " " .. s:match('^{|([^\n]*)') if arguments:match(' id *= *" *([%w%d_-]+) *"') == theId then return s       end end return nil end

function p.main(frame) return p._main(getArgs(frame, {wrappers = 'Template:Table row counter'})) end

function p._main(args) mw.log("Table row counter", "page=", args.page, "id=", args.id) -- Get the title object. local titleObj = p.getTitleObj(args.page)

-- Get the page content. local content = titleObj:getContent if not content then mw.log("Warning: no page content") return "(?)" end

-- Find the wikitables on that page. local allWikitables = p.getAllTables(content)

-- Find the wikitable to work on. local wikitable if args.id then wikitable = p.getTableById(allWikitables, args.id) else mw.log('No ID specified; using tableno') wikitable = allWikitables[tonumber(args.tableno) or 1] end if not wikitable then mw.log("Warning: the requested wikitable could be found") return "(?)" 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:find('^{|[^\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. count = count - (tonumber(args.ignore) or 0) if count < 0 then count = 0 end return count end

return p