Module:诗歌分类

維基文庫,自由的圖書館
文档图示 模块文档[创建]
local m = {}

local data_src = {'字数', '体裁', '题材', '时代'}
local data = {}
for _, name in ipairs(data_src) do
	table.insert(data, mw.loadJsonData('Module:诗歌分类/' .. name .. '.json'))
end

local handle_cat_single
local handle_cat_group

function handle_cat_single(args, result, data_cat, str_cat)
	local item_cat = data_cat[str_cat]
	if type(item_cat) == 'string' then
		table.insert(result, item_cat)
	elseif type(item_cat) == 'table' then
		if type(item_cat[1]) == 'string' then
			for _, item_cat_sub in ipairs(item_cat) do table.insert(result, item_cat_sub) end
		else
			local name = item_cat['名称']
			if type(name) == 'string' then
				table.insert(result, name)
			elseif type(name) == 'table' and type(name[1]) == 'string' then
				for _, item_cat_sub in ipairs(name) do table.insert(result, item_cat_sub) end
			end
			
			if type(item_cat['复合']) == 'table' then
				handle_cat_group(args, result, {item_cat['复合']})
			end
		end
	end
end

function handle_cat_group(args, result, data_cat)
	for index, arg in pairs(args) do
        if type(index) == 'number' then
            if index == 1 then
                for str_cat in arg:gmatch'[\1-\255][\128-\191]*' do
                    for _, data_sub in ipairs(data_cat) do handle_cat_single(args, result, data_sub, str_cat) end
                end
            else
                for _, data_sub in ipairs(data_cat) do handle_cat_single(args, result, data_sub, arg) end
            end
        end
    end
end

function m.cat(frame)
	local result = {}
	
	handle_cat_group(frame:getParent().args, result, data)
	
	if #result > 0 then
		return '[[分类:' .. table.concat(result, ']][[分类:') .. ']]'
	else return '' end
end

function m.doc(frame)
	local r = {}
	for i = 1, #data_src do
		table.insert(r, '* ' .. data_src[i] .. '类 <small>([[Special:EditPage/Module:诗歌分类/' .. data_src[i] .. '.json|编辑]])</small>')
		for k, v in pairs(data[i]) do
			local cat_name = v
			if type(cat_name) ~= 'string' then cat_name = v[1] end
			if type(cat_name) ~= 'string' then cat_name = v['名称'] end
			if type(cat_name) == 'string' then
				table.insert(r, '** <b>' .. k .. '</b>: [[:分类:' .. cat_name .. ']]')
			end
		end
	end
	return table.concat(r, '\n')
end

return m