モジュール:String

提供: 2ちゃんねるウィキペディアスレまとめwiki
Jump to navigation Jump to search

このモジュールについての説明文ページを モジュール:String/doc に作成できます

local p = {}

local a, s
local function defineArgs(frame)
	a = frame.args or frame:getParent().args
	s = a.s or a.source or a[1]
end

local falses = {'false', 'nil', '0', ''}
local function toboolean(str)
	for i, v in ipairs(falses) do
		if str == v then return false end
	end
	return true
end

local function escapePatterns(pattern)
	return mw.ustring.gsub(pattern, '[%%%(%)%[%]%^%$%.%*%+%-%?]', '%%%0')
end

function p.byte(frame)
	defineArgs(frame)
	local i, j = tonumber(a.i or a[2]), tonumber(a.j or a[3])
	return mw.ustring.byte(s, i, j)
end

function p.byteoffset(frame)
	local l, i = tonumber(a.l or a[2] or 1), tonumber(a.i or a[3] or 1)
	return mw.ustring.byteoffset(s, l, i)
end

function p.codepoint(frame)
	defineArgs(frame)
	local i, j = tonumber(a.i or a[2]), tonumber(a.j or a[3])
	return mw.ustring.codepoint(s, i, j)
end

function p.find(frame)
	defineArgs(frame)
	local pattern, init, plain = a.pattern or a[2], tonumber(a.init or a[3] or 1), toboolean(a.plain or a[4])
	return mw.ustring.find(s, pattern, init, plain)
end

function p.format(frame)
	defineArgs(frame)
	local na = {}
	for i in ipairs(a) do
		na[i] = a[i]
	end
	return mw.ustring.format(unpack(na))
end

function p.gsub(frame)
	defineArgs(frame)
	local pattern, repl, n, plain = a.pattern or a[2], a.repl or a[3], tonumber(a.n or a[4] or nil), toboolean(a.plain or a[5])
	if plain then pattern = escapePatterns(pattern) end
	return (mw.ustring.gsub(s, pattern, repl, n))
end
p.replace = p.gsub

function p.len(frame)
	defineArgs(frame)
	return mw.ustring.len(s)
end
p.length = p.len

function p.match(frame)
	defineArgs(frame)
	local pattern, init, plain = a.pattern or a[2], tonumber(a.init or a[3] or 1), toboolean(a.plain or a[4])
	if plain then pattern = escapePatterns(pattern) end
	return mw.ustring.match(s, pattern, init)
end

function p.rep(frame)
	defineArgs(frame)
	local n = tonumber(a.n or a[2] or 1)
	return mw.ustring.rep(s, n)
end
p['repeat'] = p.rep

function p.reverse(frame)
	defineArgs(frame)
	local result = ''
	for i = 1, mw.ustring.len(s) do
		result = result .. mw.ustring.sub(s, -i, -i)
	end
	return result
end

function p.sub(frame)
	defineArgs(frame)
	local i, j = tonumber(a.i or a[2] or 1), tonumber(a.j or a[3] or -1)
	return mw.ustring.sub(s, i, j)
end
p.substring = p.sub

return p