lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Am 13.08.2013 20:23 schröbte Bernd Eggink:
The documentation says, "the q option formats a string between double
quotes, using escape sequences when necessary to ensure that it can
safely be read back by the Lua interpreter".
However, this is not true if the string contains certain escape
sequences, such as \027 or \013:

     t="\027[1maha\027[m"
     t1=string.format("%q", t)    --> "\27[1maha\27[m"

On an xterm in Linux print(t) prints a nice bold aha, while print(t1)
prints "\27[1maha\27[m". Is that a bug or am I missing something?

Yes, you are missing the "can safely be read back by the Lua interpreter". You are not reading t1 back. Try this instead:

    t = "\027[1maha\027[m"
    print( t )
    file = assert( io.open( "f.lua", "w" ) )
    -- %q already includes double quotes at both ends ...:
    file:write( "print(", string.format( "%q", t ), ")\n" )
    file:close()
    dofile( "f.lua" )  -- do the reading back ...

So, the %q format specifier is for generating valid Lua string literals that can be pasted into a Lua program ...


Bernd


Philipp