Browse Source

when formatting with '%q', all control characters are coded
as \nnn.

Roberto Ierusalimschy 18 years ago
parent
commit
d62a21b9d3
1 changed files with 14 additions and 19 deletions
  1. 14 19
      lstrlib.c

+ 14 - 19
lstrlib.c

@@ -1,5 +1,5 @@
 /*
-** $Id: lstrlib.c,v 1.134 2006/09/11 14:07:24 roberto Exp roberto $
+** $Id: lstrlib.c,v 1.135 2006/09/18 16:33:14 roberto Exp roberto $
 ** Standard library for string operations and pattern-matching
 ** See Copyright Notice in lua.h
 */
@@ -697,25 +697,20 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
   const char *s = luaL_checklstring(L, arg, &l);
   luaL_addchar(b, '"');
   while (l--) {
-    switch (*s) {
-      case '"': case '\\': case '\n': {
-        luaL_addchar(b, '\\');
-        luaL_addchar(b, *s);
-        break;
-      }
-      case '\r': {
-        luaL_addlstring(b, "\\r", 2);
-        break;
-      }
-      case '\0': {
-        luaL_addlstring(b, "\\000", 4);
-        break;
-      }
-      default: {
-        luaL_addchar(b, *s);
-        break;
-      }
+    if (*s == '"' || *s == '\\' || *s == '\n') {
+      luaL_addchar(b, '\\');
+      luaL_addchar(b, *s);
     }
+    else if (*s == '\0' || iscntrl(uchar(*s))) {
+      char buff[10];
+      if (*s != '\0' && !isdigit(uchar(*(s+1))))
+        sprintf(buff, "\\%d", uchar(*s));
+      else
+        sprintf(buff, "\\%03d", uchar(*s));
+      luaL_addstring(b, buff);
+    }
+    else
+      luaL_addchar(b, *s);
     s++;
   }
   luaL_addchar(b, '"');