[Top][All Lists]

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

Re: Checking parameters

From: Tim X
Subject: Re: Checking parameters
Date: Sun, 17 Jun 2007 23:18:54 +1000
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/22.1.50 (gnu/linux)

Cecil Westerhof <address@hidden> writes:

> I am new to Emacs and lisp.
> What is the best way to check parameters and do error handling when they are
> not correct?
> I have the following function:
> (defun getHours(time)
>   (interactive "sHH:MM: ")
>   (let ((timelist (split-string time ":")))
>     (+
>       (string-to-number (car timelist))
>       (/
>         (string-to-number (cadr timelist))
>         60.0
>       )
>     )
>   )
> )
> How do I check that there is exactly one parameter? And how do I check the
> format and give an error that works in interactive and normal mode?
> For example when I give
>     (getHours "0:120")
> I get
>     2.0
> How should I generate an error/exception?

Emacs will throw an error if the function is called with the wrong number of

There is already a reply that shows a simple way to check for the correct
string format using a regexp. However, if you want to get a bit more
adventurous and you would like a function that can tell the user the arguement
is invalid and give them another opportunity to enter a correctly formatted
argument, you might want to use a function instead of the prompt sring. This
function can then prompt the user for input, check that it is valid and if it
is, just returns the values as a list (which may only have one element if thats
all that is required). If the value the user entered was not a valid format,
the function can print an error message, possibly explaining why the users
input was no good and then prompt again to give the user another go. 

While this may take more work, it can be nicer for the end user. It can
sometimes also make your code look a bit cleaner as you can put the arguement
error checking off in its own function, rather than have it cluttering up the
main body of your function. 

for example (untested)

(defun time-prompt ()
  "Prompt for a valid time string HH:MM."
  (let (prompt-str)
    (setq prompt-str (read-from-minibuffer "Time HH:MM: "))
    (while (not (string-match "^[0-9]+:[0-5][0-9]$" prompt-str))
      (message "Bad time format. Must be HH:MM")
      (setq prompt-str (read-from-minibuffer "Time HH:MM: ")))
    (list prompt-str)))

(defun getHours(time)
  (interactive time-prompt)


tcross (at) rapttech dot com dot au

reply via email to

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