Shko te përmbajtja

Moduli:Escape

Nga Wikipedia, enciklopedia e lirë
-- Module:Escape
local p = {}

-- Safely escape HTML characters
function p.text(s)
    if not s then return '' end
    s = tostring(s)
    s = s:gsub("&", "&")
    s = s:gsub("<", "&lt;")
    s = s:gsub(">", "&gt;")
    return s
end

-- Undo escaping of HTML characters
function p.undo(s)
    if not s then return '' end
    s = tostring(s)
    s = s:gsub("&amp;", "&")
    s = s:gsub("&lt;", "<")
    s = s:gsub("&gt;", ">")
    return s
end

-- Optional: escape custom characters
-- Usage: escape:char("x"):text("some text")
local escape_mt = {}
escape_mt.__index = escape_mt

function escape_mt:char(chr, args)
    args = args or {}
    chr = tostring(chr or '\\')
    self.char = chr
    return self
end

function escape_mt:text(text)
    if not text then return '' end
    text = tostring(text)
    if self.char then
        text = text:gsub(self.char, string.format("&#%d;", self.char:byte()))
    end
    return text
end

function escape_mt:undo(text)
    if not text then return '' end
    text = tostring(text)
    if self.char then
        text = text:gsub("&#" .. self.char:byte() .. ";", self.char)
    end
    return text
end

function p.main(frame)
    local args = frame.args or {}
    local e = setmetatable({}, escape_mt)
    if args.mode == "char" then
        return e:char(args.char or args[1], args)
    end
    return e
end

return p