help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: use of "match-string"


From: Tim X
Subject: Re: use of "match-string"
Date: Wed, 09 Mar 2011 08:36:17 +1100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.0.50 (gnu/linux)

ken <address@hidden> writes:

> Part of this function doesn't make sense--
>
> (defun html-toc-find-max ()
>   (goto-char (point-min))
>   (let ((max-toc 0))
>     (while (search-forward-regexp html-toc-tocref nil t)
>       (if (> (string-to-int (match-string 1)) max-toc)
>           (setq max-toc (string-to-int (match-string 1)))))
>     (1+ max-toc)))
>
> -- specifically, where match-string is first called and turned into a
> number.  The docs say that match-string returns a string....  Yes, this
> can be done I suppose, but to what end?  Moreover, depending upon its
> value, this "number" may then be assigned to a variable, and that value
> then compared with subsequent strings.
>
> Perhaps I'm missing some nuance here.  The entirety of the code is
> below.  Does anyone understand what's going on here?
>

I'm not sure what it is you find 'odd' about the above function. Apart
from the fact it should be using string-to-number (string-to-int has
been marked obsolete since 22.1), it seems reasonable to me. 

The regexp used in the match is 

> (defvar html-toc-tocref     (concat "<A NAME=\"" html-toc-name-pre
>                                     "\\([0-9]*\\)\">"))

Note the 1st (and only) grouping in the regexp i.e. \\([0-9]*\\), which
will match on 0 or more digits between 0..9. This is what (match-string
1) will return. (though as it is [0-9]* it could return 0 or more
digits, so match-string 1 could be "", which may be an issue).

The string-to-int call will return that value as a number rather than as
a string, which is then compared to max-toc (initially set to 0), not to
a string. The final value has 1 added to it. So, your not comparing
strings, you are comparing strings of numers that are converted to be a number.

So, this function would search through the buffer for the specified
regexp, extract the group of digits as a string, convert them to a
number and compare them to the last one found. If the number is larger,
it would set that as the max and then continue the loop. Finally, it
adds 1. 

I can see some things I would do differently and even if you don't find
a match, your max-toc value will have a value of at least 1, but apart
from that, it seems to do whatever it was intended to do. 

Tim


-- 
tcross (at) rapttech dot com dot au


reply via email to

[Prev in Thread] Current Thread [Next in Thread]