Module:Escape
Appearance
escape = {
init = function(self, char, args)
args = args or {}
local safe = {
args.front or string.char(24),
args.back or string.char(27)
}
char = tostring(char)
self[1] = ('%s%%s%s'):format(
('%s%s%s'):format(safe[1], ('%x'):format(char:byte()), safe[1]),
('%s%s'):format(safe[2], ('%x'):format(char:byte()))
)
if not self[self[1]] then
self[self[1]] = {
char = char,
text = ('%s(.)'):format(char),
undo = self[1]:format'(%d+)'
}
end
return args.text and self:text(args.text)
or args.undo and self:undo(args.undo, char)
or self
end,
exec = function(self, text, pattern, newEscape)
local target, v = self[self[1]]
repeat v = text:match(target[pattern])
text = v and
text:gsub(
pattern == 'text' and
('%s%s'):format(target.char, v)
or self[1]:format(v),
pattern == 'text' and
self[1]:format(v:byte())
or (newEscape or '') .. v:char()
)
or text
until not v
return text
end,
text = function(self, text)
return self:exec(text, 'text')
end,
undo = function(self, text, newEscape)
return self:exec(text, 'undo', newEscape)
end
}
return escape:init('\\')