Save original function, locally rebind it with flet and call original function from inside new?

痞子三分冷 提交于 2019-12-11 01:58:56

问题


subj. Something like:

(lexical-let (oldf #'original-func)
   (flet ((original-func (arg)
             do-something
             (funcall oldf arg))) 
      do-something))

don't work :(


回答1:


Hopefully this will help you with the syntax, calling swap-function calls foo1 but executes foo2.

You could write this as a useful macro with-replace-function which binds the old function with the new function while executing a body you pass in.

(defun foo1()
  (insert "hi foo1"))

(defun foo2()
  (insert "hi foo2"))

(defun swap-function(old new)
  (let ((save-func (symbol-function old)))
    (fset old (symbol-function new))
    (funcall old)
    (fset old save-func)))

(swap-function #'foo1 #'foo2)



回答2:


There is no reader macros in emacs-lisp, you need to use symbol-function explicitly.

(defun test-1 (x)
  (message "base test %s" x))

(let ((old-test-1 (symbol-function 'test-1))
      (z 10))
  (flet ((test-1 (y)
           (funcall old-test-1 y)
           (message "extended test %s" y)))
    (nic-test-1 z)))

If you want to use it as a closure you'll need to use lexical-let instead of let or set lexical-binding to T.



来源:https://stackoverflow.com/questions/9150569/save-original-function-locally-rebind-it-with-flet-and-call-original-function-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!