Skip to content

Instantly share code, notes, and snippets.

@MasWag
Created June 25, 2023 04:18
Show Gist options
  • Select an option

  • Save MasWag/337f91bfe149ad2e1083f142dd3f124a to your computer and use it in GitHub Desktop.

Select an option

Save MasWag/337f91bfe149ad2e1083f142dd3f124a to your computer and use it in GitHub Desktop.
Brief example showing dynamic binding and lexical binding in Emacs Lisp
;;; Brief example showing dynamic binding and lexical binding in Emacs Lisp (Comments are in Japanese)
;;; Lines staring with ";>" show the output produced in the REPL.
;; lexical bindingを無効化してdynamic bindingを使う
(setq lexical-binding nil)
;> nil
(defun retcl (x)
(lambda () (+ x 1)))
;> retcl
(setq f (retcl 10))
;> (lambda nil (+ x 1))
;; retcl内の変数環境ではなく呼出時の変数環境が使われるので、結果は21になる
(let ((x 20))
(funcall f))
;> 21
;; lexical bindingを有効化して、同じ例を動かす
(setq lexical-binding t)
;> t
(defun retcl (x)
(lambda () (+ x 1)))
;> retcl
;; そもそもこの時点で (x . 10) という環境の元でのclosureということが表示されているが…
(setq f (retcl 10))
;> (closure ((x . 10) t) nil (+ x 1))
;; 呼出時の変数環境ではなくretcl内の変数環境が使われるので、結果は11になる
(let ((x 20))
(funcall f))
;> 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment