help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: Real-life examples of lexical binding in Emacs Lisp


From: Pascal J. Bourguignon
Subject: Re: Real-life examples of lexical binding in Emacs Lisp
Date: Sun, 14 Jun 2015 23:44:45 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Stefan Monnier <monnier@iro.umontreal.ca> writes:

>>> However, I would argue that for global variables, lexical binding would
>>> be useful too, even by default.
>
> I'm not sure what that means.  But you can set a global value to
> a variable without declaring it as dynamically scoped:
>
>     (setq my-lex-var 3)

Wrong.

Having a file lex.el:
------------------------------------------------------------------------
;; -*- mode:emacs-lisp; lexical-binding:nil -*-

(setq lexical? 33)
(defun f ()
  lexical?)
(defun g ()
  (let ((lexical? 42))
    (f)))

(print (g))
------------------------------------------------------------------------

Then M-x load-file RET lex.el RET writes 42 in *Message* which shows
that lexical? IS a dynamic variable!  If it was lexical, we would get
33, because the lexical scope of the closure f is the global scope,
where lexical? as been bound to 33, not the local dynamic scope of the
function g when the variable lexical? is bound to 42.


> Inside Emacs we also have a few global vars (e.g. `pi' and `argv') which
> we would want to declare with something like defvar for various reasons
> (providing a docstring, recording where is the declaration, etc...) yet
> we don't want them to be dynamically scoped.
>
> For `pi' we just used `setq', and for `argv' we used defvar followed by
> an ugly hack called internal-make-var-non-special.
>
>
>         Stefan

-- 
__Pascal Bourguignon__                 http://www.informatimago.com/
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk


reply via email to

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