Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;;; dynvar.lisp
- ;;; S. Edward Dolan
- ;;; Wednesday, May 1 2019
- ;;;
- ;;; If you call FN1 the output will be:
- ;;;
- ;;; global *foo* value: 42
- ;;; fn1 *foo* value: 99
- ;;; fn2 *foo* value: 99
- ;;; fn3 *foo* value: 99
- ;;; fn1 *foo* value: 0.0333
- ;;; global *foo* value: 42
- ;;; The thing to note here is the program isn't explicitly saving and
- ;;; restoring the values. Lisp handles it behind the scenes.
- (defvar *foo* 42) ;globally bind *foo* to 42
- (defun fn1 ()
- (format t " global *foo* value: ~S~%" *foo*)
- (let ((*foo* 99)) ;dynamically bind *foo* to 99
- (format t " fn1 *foo* value: ~S~%" *foo*)
- (fn2) ;call fn2
- (format t " fn1 *foo* value: ~S~%" *foo*))
- ;; The global binding is reinstated when the LET form completes
- (format t " global *foo* value: ~S~%" *foo*))
- (defun fn2 ()
- ;; Here, *foo* retains the value bound in fn1
- (format t " fn2 *foo* value: ~S~%" *foo*)
- (fn3) ;call fn3
- ;; You can reset the var at-will and only the current binding will be
- ;; affected. Now fn1 will see this value.
- (setf *foo* 33.3e-3))
- (defun fn3 ()
- ;; Again, *foo* retains the value bound in fn1
- (format t " fn3 *foo* value: ~S~%" *foo*)
- ;; You could rebind it again here in a LET form and any function called
- ;; within the body of the LET will see that value.
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement