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

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

Re: Set (global) function argument from inside function


From: Thorsten Jolitz
Subject: Re: Set (global) function argument from inside function
Date: Mon, 11 Aug 2014 09:53:46 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

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

>>  (defun foo (X)
>>    (setq X (+ X 5)))
>>
>>  (setq Y 2)
>>  (message "fooY: %s Y: %s" (foo Y) Y)
>
>> #+results:
>> : fooY: 7 Y: 2
>
> IIUC you want to pass a variable by reference. 

Exactly. Funny that I know the terminology in and out, but did not
relate it to the real-world problem.

> Elisp does not offer to pass arguments by reference (contrary to, say,
> C++).  But just like C, it lets you construct references and pass
> them:
>
>   (defun foo (X-ref)
>     (setf (gv-deref X-ref) (+ (gv-deref X-ref) 5)))
>
>   (setq Y 2)
>   (message "fooY: %s Y: %s" (foo (gv-ref Y)) Y)
>
> Note that gv-ref only exists in Emacs>24.3 and only works with
> lexical-binding.

did not know about the gv.el library, and do not have the version with
`gv-deref' yet, but this definitely looks interesting.

> If you only care about global variables (rather than arbitrary "place"s,
> such as global vars, local vars, array elements, list elements, ...),
> and you want it to work with older Emacsen, you can use the following
> instead:

#+BEGIN_SRC emacs-lisp
   (defun foo (X-name)
     (set X-name (+ (symbol-value X-name) 5)))
#+END_SRC

#+results:
: foo

#+BEGIN_SRC emacs-lisp
   (setq Y 2)
   (message "fooY: %s Y: %s" (foo 'Y) Y)
#+END_SRC

#+results:
: fooY: 7 Y: 7


Exactly what I need, thank you!

-- 
cheers,
Thorsten




reply via email to

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