(其他人已回答你的直接問題灰。但是,這可能會回答你的問題背後的問題,並說出你真正想做的事情。如果不是看到其他的答案。)
你做不需要一個宏可言,做你想做的。只需使用defalias
或fset
即可。每個是函數。
(defun foo (cmd &optional search)
(let ((fn (intern (concat "fn-" cmd))))
(defalias fn `(lambda (&optional args)
(let ((str (symbol-name ',fn))
,@(when search
'((dir "~"))))
(message "Called %S from %S" str
(or (and (bound-and-true-p 'dir) dir)
default-directory)))))))
(dolist (x '("f1" "f2")) (foo x))
然後(symbol-function 'fn-f1)
回報:
(lambda (&optional args)
(let ((str (symbol-name 'fn-f1)))
(message "Called %S from %S" str (or (and (bound-and-true-p dir) dir)
default-directory))))
如果您使用詞彙結合(即,將局部變量綁定-*- lexical-binding: t -*-
置於定義此代碼的文件的頂部,然後您不需要任何反引號。例如:
(defun foo (cmd &optional search)
(let ((fn (intern (concat "fn-" cmd))))
(defalias fn (lambda (&optional args)
(let ((str (symbol-name fn))
(dir (if search "~" default-directory)))
(message "Called %S from %S" str dir))))))
(dolist (x '("f1" "f2")) (foo x))
如果你這樣做,那麼每個功能fn-f1
和fn-f2
被定義爲一個封閉,它看起來像這樣:
(symbol-function 'fn-f1)
(closure
((fn . fn-f1)
(search)
(cmd . "f1")
t)
(&optional args)
(let ((str (symbol-name fn))
(dir (if search "~" default-directory)))
(message "Called %S from %S" str dir)))
而且(foo "f3" :SEARCH)
定義一個函數fn-f3
(封閉)封裝否則自由變量search
與非nil
值:SEARCH
的綁定,使得局部變量dir
變爲綁定到"~"
:
(symbol-function 'fn-f3)
(closure
((fn . fn-f3)
(search . :SEARCH) ;; <==============
(cmd . "f3")
t)
(&optional args)
(let ((str (symbol-name fn))
(dir (if search "~" default-directory)))
(message "Called %S from %S" str dir)))