# Error in PiL3 in Listing 12.1 (page 121) Classic List Threaded 5 messages Open this post in threaded view
|

## Error in PiL3 in Listing 12.1 (page 121)

 Function quote() gives incorrect result for some input strings, for example "]]=]"BTW, PiL2 contains correct (but not optimal) code for this function.  A correct code may look like the following:  function quote (s)    -- find maximum length of sequences of equal signs    local n = -1    for w in string.gmatch(s, "]([]=]*)]") do       for e in string.gmatch(w, "=*") do          n = math.max(n, #e)       end    end    -- The rest of the code is exactly the same as in the book  Probably, it is more important for code to be simple and beginner-friendly than correct.   Instead of modifying code of Listing 12.1 this issue may be solved by introducing an exercise: "Find an input string on which function quote() fails to get correct result. Rewrite the function to fix this error."-- Egor
Open this post in threaded view
|

## Re: Error in PiL3 in Listing 12.1 (page 121)

 Hi Egor > A correct code may look like the following: > > function quote (s) >    -- find maximum length of sequences of equal signs >    local n = -1 >    for w in string.gmatch(s, "]([]=]*)]") do >       for e in string.gmatch(w, "=*") do >          n = math.max(n, #e) >       end >    end >    -- The rest of the code is exactly the same as in the book I test your code but it seems it does not handle all cases at all: Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio > function quote(s) >>     local n = -1 >>     for w in string.gmatch(s, "]([]=]*)]") do >>         for e in string.gmatch(w, "=*") do >>             n = math.max(n, #e) >>         end >>     end >>     local eq = string.rep("=", n+1) >>     return string.format(" [%s[\n%s]%s] ", eq, s, eq) >> end > print(quote"]=]==")   [==[ ]=]==]==] > Regards, Tomás
Open this post in threaded view
|

## Re: Error in PiL3 in Listing 12.1 (page 121)

 On Sun, Jul 5, 2015 at 3:34 PM, tomas wrote:I test your code but it seems it does not handle all cases at all:print(quote"]=]==")  [==[ ]=]==]==]Oops!  Indeed...   My bad.This error can be fixed by appending a closing bracket to the input string before processing:function quote (s)    -- find maximum length of sequences of equal signs    local n = -1    for w in string.gmatch(s.."]", "]([]=]*)]") do       for e in string.gmatch(w, "=*") do          n = math.max(n, #e)       end    end    -- The rest of the code is exactly the same as in the book