local export = {}
local UTF8_char = "[%z\1-\127\194-\244][\128-\191]*"
function export.iterChar(str)
return string.gmatch(str, UTF8_char)
end
function export.fetch(str, index)
if index <= 0 then
error("Second argument to fetch must be a positive integer.")
end
local i = 0
for char in iter_char(str) do
i = i + 1
if i == index then
return char
end
end
return ""
end
function export.gsub_with_escapes(frame)
local params = {
[1] = { required = true, allow_empty = true },
[2] = { required = true, allow_empty = true },
[3] = { required = true, allow_empty = true },
[4] = { type = "number" },
extra = { type = "boolean" },
}
local args = require("Module:parameters").process(frame.args, params)
local letter_escapes = {
a = "\a", b = "\b", f = "\f", n = "\n", r = "\r", t = "\t", v = "\v",
}
for i = 1, 3 do
args[i] = args[i]
:gsub("\\([abfnrtv])", letter_escapes)
:gsub("\\(%d%d?%d?)", string.byte)
-- Pretend that Lua 5.1 has Lua 5.3 escapes.
if args.extra then
args[i] = args[i]
:gsub("\\u{(%x+)}", function (hex)
return mw.ustring.char(tonumber(hex, 16))
end)
:gsub("\\x(%x%x)", function (hex)
return string.char(tonumber(hex, 16))
end)
end
end
return (mw.ustring.gsub(args[1], args[2], args[3], args[4]))
end
return export