Module:Array

From NeuroWiki
Jump to navigation Jump to search

此模块可将一个Lua table或一个字符串按给定的分隔符输出语言自然的列表。


local p = {}

local function stringToArray(str, separator, mapper)
	local arr = {}
	local i = 1
	for v in mw.text.gsplit(str, separator) do
		arr[i] = mapper(v)
		i = i + 1
	end
	return arr
end

local function tableToArray(tbl, offset, mapper)
	local arr = {}
	for k, v in pairs(tbl) do
		if type(k) == 'number' and k > offset then
			arr[k - offset] = mapper(v)
		end
	end
	return arr
end

function p.main()
	local args = require('Module:ProcessArgs').merge()
	return p.array(args)
end

function p.array(args)
	local wrapTag = args.wrap or ''
	local wrapTemplate = args.template or ''
	local delimiter = args.delimiter or args.d
	local formatString = args.format
	local finalDelimiter = args.finaldelimiter or args.fd

	local frame = mw.getCurrentFrame()

	local mapper = type(args.mapper) == 'function'
		and args.mapper
		or function (v)
			if wrapTemplate ~= '' then
				v = require( 'Module:' .. wrapTemplate ).call{ v }
			end
			if wrapTag ~= '' then
				if wrapTag == 'nowiki' then
					v = mw.text.nowiki(mw.text.unstripNoWiki(v))
				else
					v = frame:extensionTag(wrapTag, v)
				end
			end
			if formatString then
				v = formatString:format(v, v)
			end
			return v
		end

	local arr
	if args.mode == 'single' then
		arr = stringToArray(args[1], args.sep or ',', mapper)
	else
		arr = tableToArray(args, tonumber(args.offset) or 0, mapper)
	end

	if arr[1] == nil then
		return ''
	end

	if delimiter == 'pretty' then
		return mw.text.listToText(arr, nil, finalDelimiter ~= '' and finalDelimiter or nil)
	elseif finalDelimiter then
		return mw.text.listToText(arr, delimiter, finalDelimiter)
	elseif delimiter == 'newline' or delimiter == 'br' then
		return table.concat(arr, '<br>')
	elseif delimiter == 'list' or delimiter == 'list-newline'
		or delimiter == 'bullet' or delimiter == '*' then
			local listLevel = args['list-level'] or '**'
			return table.concat(arr, '\n' .. listLevel)
	else
		return table.concat(arr, delimiter)
	end
end

return p