From b29a8af7434eca71dd56094f0a20fef6d683212e Mon Sep 17 00:00:00 2001 From: Pavel Labath Date: Fri, 19 Aug 2011 00:23:09 +0200 Subject: Add lua::quote function, for safe (and pretty) quoting of strings --- src/FbTk/Luamm.cc | 24 ++++++++++++++++++++++++ src/FbTk/Luamm.hh | 4 ++++ 2 files changed, 28 insertions(+) diff --git a/src/FbTk/Luamm.cc b/src/FbTk/Luamm.cc index 8824b06..3b0c4ba 100644 --- a/src/FbTk/Luamm.cc +++ b/src/FbTk/Luamm.cc @@ -219,6 +219,30 @@ namespace lua { l->replace(-2); } + std::string quote(const std::string &str) + { + std::string bad = "\n\\"; + bad += '\0'; + + // first try to quote using normal quotes without escaping + if(str.find_first_of(bad + '"') == std::string::npos) + return '"' + str + '"'; + else if(str.find_first_of(bad + '\'') == std::string::npos) + return '\'' + str + '\''; + + // use long quotes + bad.clear(); + + // find the first long quote that works + while(str.find(']' + bad + ']') != std::string::npos) + bad += '='; + + std::string out = '[' + bad + '['; + if(str.find('\n') != std::string::npos) + out += '\n'; + return out + str + ']' + bad + ']'; + } + state::state() : cobj(luaL_newstate()), valid(new bool(true)) { diff --git a/src/FbTk/Luamm.hh b/src/FbTk/Luamm.hh index 01fb8b1..245d77b 100644 --- a/src/FbTk/Luamm.hh +++ b/src/FbTk/Luamm.hh @@ -139,6 +139,10 @@ namespace lua { {} }; + // format the string in a form that can be safely read back by the lua interpreter + // tries to make the string a bit nicer than the lua's %q format specifier + std::string quote(const std::string &str); + // a fancy wrapper around lua_State class state { lua_State *cobj; -- cgit v0.11.2