How to define a function which repeats itself when passed an argument

Posted by ~unutbu on Stack Overflow See other posts from Stack Overflow or by ~unutbu
Published on 2010-05-11T14:04:55Z Indexed on 2010/05/11 15:04 UTC
Read the original article Hit count: 195

Filed under:
|

Is there an easy way to define a function which repeats itself when passed an argument?

For example, I've defined the following function

(defun swap-sign ()
  (interactive)
  (search-forward-regexp "[+-]")
  (if (equal (match-string 0) "-")
      (replace-match "+")
    (replace-match "-"))
  )

I'd like C-u swap-sign to call swap-sign four times.

I've tried

(defun swap-sign (&optional num)
  (interactive)
  (let ((counter 0)
 (num (if num (string-to-number num) 0)))
    (while (<= counter num)
      (search-forward-regexp "[+-]")
      (if (equal (match-string 0) "-")
   (replace-match "+")
 (replace-match "-"))           
      (setq counter (1+ counter)))))

but C-u swap-sign still only runs swap-sign (or perhaps more precisely, the body of the while-loop) once. I'm guessing it is because if num is not the right way to test if num is an empty string.

Am I on the right track, or is there a better/easier way to extend swap-sign?

© Stack Overflow or respective owner

Related posts about emacs

Related posts about elisp