Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Primer on representing non-printable characters in Lua code
- function assert_equal(a, b)
- if a ~= b then
- error(a .. ' is not equal to ' .. b)
- end
- end
- -- Escape sequences in string use decimal character codes, i.e.
- assert_equal('\97\98\99', 'abc')
- -- Bytes in the string can be retrieved with string.byte(s, 0, -1)
- local bytes = {string.byte('abc', 0, -1)} -- type(bytes) == 'table', #bytes == 3
- assert_equal(table.concat(bytes, ', '), '97, 98, 99')
- -- print(s) prints octal encoded escape sequences (WTF?)
- print('\128') -- will print '\200'
- -- To get the string which can be put back into source file you can
- local eprint = function(s) print('\\' .. table.concat({string.byte(s, 0, -1)}, '\\')) end
- eprint('abc') -- will print '\97\98\99'
- -- Or to keep printable chars
- local eprint = function(s)
- local bytes = {}
- for i=1,#s do
- local byte = string.byte(s, i)
- if byte >= 32 and i <= 126 then
- byte = string.char(byte)
- else
- byte = '\\' .. tostring(byte)
- end
- table.insert(bytes, byte)
- end
- print(table.concat(bytes))
- end
- -- Print string with non printable characters to be put in source code
- -- "string with non printable".bytes.to_a.map {|i| i >= 32 && i <= 126 ? i.chr : "\\#{i}" }.join
- -- String from Ruby to Lua
- > '\\' + abc'.unpack('C*') * '\\' # => "\\97\\98\\99"
- -- From Lua bytes to Ruby string
- > [97, 98, 99].pack('c*')
- "abc"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement