github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/luastrings/escape.go (about) 1 package luastrings 2 3 import ( 4 "strconv" 5 "strings" 6 "unicode" 7 ) 8 9 var names = []byte("abtnvf") 10 11 // Quote a string so that it is a valid Lua string literal 12 func Quote(s string, quote byte) string { 13 var b strings.Builder 14 b.WriteByte(quote) 15 for _, c := range []byte(s) { 16 switch { 17 case c == quote: 18 b.WriteByte('\\') 19 b.WriteByte(c) 20 case unicode.IsGraphic(rune(c)): 21 b.WriteByte(c) 22 default: 23 b.WriteByte('\\') 24 if c >= 7 && c <= 13 { 25 b.WriteByte(names[c-7]) 26 } else { 27 b.WriteString(strconv.FormatInt(int64(c), 10)) 28 } 29 } 30 } 31 b.WriteByte(quote) 32 return b.String() 33 }