Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. -- Primer on representing non-printable characters in Lua code
  2. function assert_equal(a, b)
  3. if a ~= b then
  4. error(a .. ' is not equal to ' .. b)
  5. end
  6. end
  7.  
  8. -- Escape sequences in string use decimal character codes, i.e.
  9. assert_equal('\97\98\99', 'abc')
  10.  
  11. -- Bytes in the string can be retrieved with string.byte(s, 0, -1)
  12. local bytes = {string.byte('abc', 0, -1)} -- type(bytes) == 'table', #bytes == 3
  13. assert_equal(table.concat(bytes, ', '), '97, 98, 99')
  14.  
  15. -- print(s) prints octal encoded escape sequences (WTF?)
  16. print('\128') -- will print '\200'
  17.  
  18. -- To get the string which can be put back into source file you can
  19. local eprint = function(s) print('\\' .. table.concat({string.byte(s, 0, -1)}, '\\')) end
  20. eprint('abc') -- will print '\97\98\99'
  21.  
  22. -- Or to keep printable chars
  23. local eprint = function(s)
  24. local bytes = {}
  25. for i=1,#s do
  26. local byte = string.byte(s, i)
  27. if byte >= 32 and i <= 126 then
  28. byte = string.char(byte)
  29. else
  30. byte = '\\' .. tostring(byte)
  31. end
  32. table.insert(bytes, byte)
  33. end
  34. print(table.concat(bytes))
  35. end
  36.  
  37.  
  38. -- Print string with non printable characters to be put in source code
  39. -- "string with non printable".bytes.to_a.map {|i| i >= 32 && i <= 126 ? i.chr : "\\#{i}" }.join
  40.  
  41. -- String from Ruby to Lua
  42. > '\\' + abc'.unpack('C*') * '\\' # => "\\97\\98\\99"
  43.  
  44. -- From Lua bytes to Ruby string
  45. > [97, 98, 99].pack('c*')
  46. "abc"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement