lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Bradley Smith wrote:
Yuri Takhteyev wrote:
I am wondering why you find this omission so shocking?  When I ran
into the need for a function like this myself, I just added it in my
own app and moved on:

    function escape(text)
return (text or ""):gsub("&", "&amp;"):gsub(">","&gt;"):gsub("<","&lt;")
    end


Or this alternative:

function escape(text)
  local escaped = { ['<']='&lt;', ['>']='&gt;', ["&"]='&amp;' }
  return text:gsub('[<>&]', function(c) return escaped[c] end)
end

print(escape('2 < 3 & 10 > 9'))
Just a note... you don't have to make the 2nd arg of that gsub a function... you could do this for a faster approach:

-- Pull escaped 'const' out
local escaped = { ['<']='&lt;', ['>']='&gt;', ["&"]='&amp;' }
function escape(text)
 return text:gsub('[<>&]', escaped)
end

This allows gsub to skip rapidly calling a function and instead directly do the replacement... (though if you had more complicated logic, you'd have to change the setup (or pre-populate a table w/ responses [or even take advantage of metatables and have the function called only for unknown responses and cache them])