{{i}} Документація модуля[створити]
local M = {}

function M.usesProperty(frame)
  local parent = frame.getParent(frame)
  local result = ''
  local ii = 1
  while true do
    local p_num = ""
    if parent.args[ii] then p_num = string.upper(parent.args[ii]) end
    if p_num ~= "" then
      local label = mw.wikibase.label(p_num) or "БЕЗ НАЗВИ"
      local cat = "Вікіпедія:" .. p_num .. ":використовується"
      local incat = mw.site.stats.pagesInCategory( cat, all )
      if incat ~= 0 then cat = " [[:Категорія:" .. cat .. "|'''К:''']]" .. tostring( incat )
      else cat = ""
      end
    result = result .. "<li><b><i>[[d:Property:" .. p_num .. "|<small>" .. p_num .. "</small>:" .. label .. "]]</i></b> {[[d:Property talk:" .. p_num .. "|обг]]•[[d:Special:WhatLinksHere/Property:" .. p_num .. "|викор]]•" .. cat .. "}</li>"
			ii = ii + 1
   	else break
    end
  end
  return result
end



-- Модуль для функціонала Вікіданих

local function tabletostr(t,fmt,s,o,c)--не для використання на сторінках
    if type(t)=="table" then
            local f={};
            for k,v in pairs(t) do
                table.insert(f,string.format(fmt or '%s = %s',k,tabletostr(v,fmt,s,o,c)))
            end;
            table.sort(f);
            return (o or '')..table.concat(f, s or '')..(c or '')
        else return tostring(t)
        end
end

function M.wbview(ref,id)--допоміжна функція для підпису з Вікіданих
    local l=mw.wikibase.label(id);
    return l and ( l==ref and l or ref..'|'..l..(mw.ustring.lower(l)==mw.ustring.lower(ref) and '' or '<sup>*</sup>') ) or ref
end

function M.id(f)-- Елемент поточної сторінки на Вікіданих
    --Якщо викликаний із параметром, дістає id значення данної властивості, інакше повертає id сторінки
    --Другий параметр - роздільник, якщо значень кілька ("; " за замовчуванням),
    -- або можна вказати номер параметром n. Третій параметр - формат для строкової властивості,
    -- за замовчуванням "%s"
	local e = mw.wikibase.getEntityObject();        
	if f.args[1] and e then
		local function gv(i)
			local z=e.claims[f.args[1]][i].mainsnak.datavalue;
			if z.type == 'wikibase-entityid' then
				return 'Q'..z.value['numeric-id']
			else
				return string.format(f.args[3] or '%s',tabletostr(z.value,"%s",'; ','{','}'))
			end
		end
		if f.args['n'] then
			return gv(tonumber(f.args['n']))
		end
		local p,h = e.claims[f.args[1]],{}
		for n,v in pairs(p) do
			h[n] = gv(n)
		end
		return table.concat(h,f.args[2] or "; ") or '';
	else return e.id or '' end
end

function M.struc(f)-- Відлагоджувальна функція, має бути перенесена в окремий модуль
    --Структуру див. [[mw:Extension:WikibaseClient/Lua#Entity table and data structure]]
	local i,e = 1,mw.wikibase.getEntityObject();
	while f.args[i] do
		e = e[ f.args[i] ] or e[ tonumber(f.args[i]) ];
		i = i+1
	end
	return tabletostr(e,f.args['f'],f.args['s'] or '; ','{','}') or '';
end

function M.label(f)--label елементу Вікіданих у 1-му параметрі
	    local id=f.args[1]
	    	or mw.wikibase.getEntityObject().id; -- error, якщо нема елемент
	    local lang = f.args[2] or 'uk'
	    return mw.wikibase.getLabelByLang( id, lang )
end

function M.labelq(f)
	local id = f.args[1]
	local lang = f.args[2]
	local entity = mw.wikibase.getEntity(id)
	if entity and entity.labels then
		local label = entity.labels['uk']
		if label then
			return '[[:d:'..id..'|'..label.value..' <small>('..id..')</small>]]'
		     else
			return '[[:d:'..id..'|'..entity.labels['en'].value..' <small>(in English; '..id..')</small>]]'
		end
	end
end

function M.labelp(f)
	local id = f.args[1]
	local entity = mw.wikibase.getEntity(id)
	if entity and entity.labels then
		local label = entity.labels['uk']
		if label then
			return '[[:d:Property:'..id..'|'..label.value..' <small>('..id..')</small>]]'
		     else
			return '[[:d:Property:'..id..'|'..entity.labels['en'].value..' <small>(in English; '..id..')</small>]]'
		end
	end
end

function M.iwiki(f)-- Інтервікі для вказаної мови (лише з ВД)
	    if f.args[1] then
	        return mw.wikibase.getEntityObject().sitelinks[f.args[1]..'wiki'].title or '';
	    else-- список інтервік
	        local r={};
	        for k,v in pairs( mw.wikibase.getEntityObject().sitelinks ) do
	            table.insert( r, string.format(f.args['f'] or "* [[:%s:%s]]\n", v.language, v.title) )
	        end
	        return table.concat(r) or '';
	    end
end

function M.iwikiall(f)-- Усі посилання, прив'язані до елементу на ВД, у т.ч. Вікігід та Сховище
	local function try()
	    if f.args[1] then
	        return mw.wikibase.getEntityObject().sitelinks[f.args[1]].title
	    else-- список інтервік
	        local r={};
	        for k,v in pairs( mw.wikibase.getEntityObject().sitelinks ) do
	            table.insert( r, string.format(f.args['f'] or "* [[:%s:%s]]\n", v.language, v.title) )
	        end
	        return table.concat(r)
	    end
	end
	local r, result = pcall(try);
    if r then
    	return result;
    else
    	return '';
    end
end

function M.page(f)-- сторінка Укрвікі (треба перевірити) для даного елемента
    return mw.wikibase.sitelink(f.args[1]) or '';
end

  -- mw.wikibase.getEntityIdForTitle( pageTitle, globalSiteId ) — qid за назвою сторінки
function M.titleid(f) -- args: [1] = pageTitle; [2] = globalSiteId ( 'ukwiki' default )
	local function try()
	    if f.args[1] and mw.text.trim( f.args[1] ) ~='' then
	        return mw.wikibase.getEntityIdForTitle( mw.text.trim( f.args[1] ), '' and f.args[2] and mw.text.trim( f.args[2] ) )
	    end
	end
	local r, result = pcall(try);
    if r then
    	return result;
    else
    	return '';
    end
end

function M.wdprops(f)-- список усіх властивостей із ВД у вигляді, придатному для читання людиною
	local e,r,id = mw.wikibase.getEntity(),{},f.args[1];
	if id then e = mw.wikibase.getEntity(id); end
	mw.logObject(e)
	if e == nil then return ''; end
	for p,a in pairs(e.claims) do
		local label = mw.wikibase.label(p) or string.format([[d:%s]],p);
		local vals = {};
		for n,v in pairs(a) do
			local w=v.mainsnak.datavalue;
			vals[n]=(
				w.type=='wikibase-entityid'
					and '[['.. M.wbview(
					mw.wikibase.sitelink('Q'..w.value['numeric-id'])
					or 'd:Q'..w.value['numeric-id'],
					'Q'..w.value['numeric-id']
					)..']]' or tabletostr(w.value)
					)
		end
		table.insert(r, string.format(
			f.args['f'] or '\n|-\n|rowspan=%i|%s\n|%s',
	            #vals,
	            label,
	            table.concat(vals,f.args['s'] or '\n|-\n|')
	            )
	        )
	end--for
	return table.concat(r) or '';
end

return M