如何编写(简单)宏?
我需要为我正在编写的游戏编写一个宏 (with-hooks (monster method who what) &body body)
。 Monster 是一个 CLOS 对象,方法,谁是字符串,什么是函数(#' 符号)。宏扩展的效果是
(add-hook monster method who what)
,@body
(remove-hook monster method who)
我绝对不知道如何编写这样的宏,并且我将不胜感激。 我有一种毛骨悚然的感觉,这很容易,而且我有点无知。
I need to write a macro (with-hooks (monster method who what) &body body)
for a game I'm writing. Monster is a CLOS object, method and who are strings and what is a function (#' notation). The macroexpansion would be something to the effect of
(add-hook monster method who what)
,@body
(remove-hook monster method who)
I have absolutely no idea how to write such a macro, and I would appreciate some help.
I have the creepy feeling that this is easy and I'm a bit ignorant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会这样写:
一些注释:
something-var
用于确保monster
、method
、的表达式who
、what
仅按从左到右的顺序计算一次(因为这些表达式在宏体中被多次引用)。gensym
用于确保变量具有唯一的名称remove-hook
(例如,由于抛出异常而堆栈展开)。I'd write it like this:
Some notes:
something-var
s are used to ensure that expressions formonster
,method
,who
,what
are evaluated only once (because these expressions are referenced multiple times in macro body) and in left-to-right order.gensym
s are used to ensure that variables have guaranteed unique namesremove-hook
is called even in case of non-local exits (e.g., stack unwind due to exception being thrown).