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

Re: menu-item-actions



>You could also consider using the following code in
>the standard system:
>   (setq fred (make-instance 'menu-item :menu-item-title "Fred"))
>   (setf (menu-item-action-function fred)
>	 #'(lambda ()
>	      (print (menu-item-title fred))))
>

An alternative method:
You can also take advantage of the fact that lisp supports
the idea of a "closure", which means that when you define
a function, it also remembers what context it was in at the time.
This means you can write this code without having to resort
to yucky global variables.

Here, the locally bound ITEM is available to its own menu-action-function.

(make-instance 'menu
       :menu-title "Test"
       :menu-items  ; this list contains just one value: ITEM
       (list   
        (let ((item (make-instance 'menu-item 
                         :menu-item-title (format nil "Random [~a]"
                                               (random 10000)))))
          (setf (menu-item-action-function item)
	               #'(lambda () (print (menu-item-title item))))
          item)))


;;;; 
; Here's some more fun with closures:

(defun taxman-maker (rate)
  #'(lambda (x) (* x (+ 1 rate))))

? (setq massachusetts (taxman-maker .15))   ; 15% tax rate
#<COMPILED-LEXICAL-CLOSURE #xED2F76>        ; This is a function
? (funcall massachusetts 500)
575.0
? (mapcar massachusetts '(300 600 900))
(345.0 690.0 1035.0)