Creating Dialogue Boxes
In this lesson you are going to learn about how to use Lisp to create Macintosh or Windows interface features like windows and dialogue boxes.
The procedures to do this are all provided in a LispWorks library called CAPI, and their names start with capi:.
Displaying a message: capi:display-message
To display a message use the capi:display-message procedure. This is followed by a format string and a list of arguments, just like format. For example:
(capi:display-message "The sum of ~a and ~a is ~a." 3 4 (+ 3 4))
will display:
Prompting for a string: capi:prompt-for-string
This asks the user to enter a string. For example:
(capi:prompt-for-string "Think of an animal:")
will display:
and will return the string you type in.
Prompting for a number: capi:prompt-for-number
In a similar way:
(capi:prompt-for-number "How many legs does it have:")
will display:
and return the number you type in.
Asking yes or no: capi:prompt-for-confirmation
The procedure capi:prompt-for-confirmation asks a question, and lets the user answer yes or no:
(capi:prompt-for-confirmation "Are you hungry?")
This displays:
If the user clicks Yes the procedure returns T (true). If the user clicks No it returns Nil (false).
Giving the user a choice: capi:prompt-with-list and capi:prompt-for-items-from-list
Finally, the function capi:prompt-with-list takes a list and a message, and lets the user select one of the items. For example:
(capi:prompt-with-list '("red" "blue" "green" "pink") "What's your favourite colour?")
will display:
and return the value of the item you've selected.
The procedure capi:prompt-for-items-from-list is identical, except that it allows you to select any number of items, and it returns a list of the items you've selected.
A story-writing program
Finally, here's a story-writing program that puts all these procedures together:
(defun story () (let ((name (capi:prompt-for-string "What is your name:")) (food (capi:prompt-for-string "What is your favourite food:")) (colour (capi:prompt-with-list '("red" "blue" "green" "pink") "What's your favourite colour?"))) (capi:display-message "There once was a witch called ~a who liked ~a. One day ~a found some ~a ~a and ate so much that she died. The end." name food name colour food)))
To run the story program evaluate:
(story)
because there's no parameter.
Exercises
1. Try improving the program to write a longer story, and use capi:prompt-for-confirmation and if statements to add branches in the story; for example:
(capi:prompt-for-confirmation "Should the witch die at the end?")
blog comments powered by Disqus