lua-users home
lua-l archive

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


> Let's see the documented example:
> 
>         string.format('%q', 'a string with "quotes" and \n new line')
> 
> Well, if there's a new user of lua, he who doesn't really consumed the
> documents,  maybe, he is going to believe the result string is:
> 
>         "a string with \"quotes\" and \n new line"
> 
> probably.  but, very soon,  he will realize that he was sadly wrong,  because
> lua just ate half of the '\n'  -  eat 'n', left '\' :
> 
>         "a string with \"quotes\" and \ new line"
> 

Even the most casual new user can only find out that there is a `q` option 
by reading the manual, since there is no such thing in C.  The manual says:

> The q option formats a string in a form suitable to be safely read 
> back by the Lua interpreter

This is all that the user needs to know.  Thus, the following code:

    luacode = ("return %q"):format(str)    
    compiled = loadstring(luacode)              
    newstr = compiled()                  
    print (str==newstr)                 

prints `true`, no matter what `str` is, as long as it is a string.  

There is no promise that the result of the `q` option is useful for any 
other purpose than writing Lua code.  Although: the game of guessing
what `luacode` will be is quite a useful exercise for that new user you 
are talking about. ☺

Dirk