Модуль:String

Материал из Verum
Перейти к навигации Перейти к поиску

Для документации этого модуля может быть создана страница Модуль:String/doc

-- стандартные строковые функции
local str = {}

function str.replace( frame )
	local source_str = frame.args['source'] or frame.args[1] or ''
	local pattern = frame.args['pattern'] or frame.args[2] or ''

	if source_str == '' or pattern == '' then
		return source_str
	end

	local replace = frame.args['replace'] or frame.args[3] or ''
	local count = tonumber( frame.args['count'] ) or tonumber( frame.args[4] ) or 100

	local result = mw.ustring.gsub( source_str, pattern, replace, count )
	
	return result
end

function str.sub( frame )
	local s = frame.args['source'] or frame.args[1] or ''
	local i = tonumber( frame.args['first'] ) or tonumber( frame.args[2] ) or 1 --позиция первого символа
	local j = tonumber( frame.args['last'] ) or tonumber( frame.args[3] ) or -1 --позиция последнего символа
	local len = tonumber( frame.args['len'] ) or tonumber( frame.args[4] ) or 0 --длина вырезки

	if len ~= 0 then
		j = i + len - 1
	end

	return mw.ustring.sub( s, i, j )
end

function str.find( frame )
	local s = frame.args['source'] or frame.args[1] or ''
	local f = frame.args['pattern'] or frame.args[2] or ''
	local i = frame.args['i'] or frame.args[3] or 1
	local plain = frame.args['plain'] or frame.args[4] or false -- regexp

	local pos = mw.ustring.find( s, f, i , plain )

	if pos == nil then
		return 0
	end

	return pos
end

function str.len( frame )
    local s = frame.args['source'] or frame.args[1] or ''
    return mw.ustring.len( s )
end

return str