[英]Erlang - How to find the name of current function at runtime?
Can I find the name of the current function I'm in at runtime? 我可以在运行时找到当前函数的名称吗?
foo() ->
foo = find_function_name().
Is it possible to write the fun find_function_name/0? 是否可以编写有趣的find_function_name / 0? How would you do it?
你会怎么做? Does it already exist?
它已经存在了吗?
More lightweight and also not depending on the stacktrace format which can change occasionally, I'd rather use process_info/2
: 更轻量级,也不依赖于偶尔可以更改的stacktrace格式,我宁愿使用
process_info/2
:
{_, {Module, Function, Arity}} = process_info(self(), current_function)
In Function
you'll find the function name as an atom and you get the Module
and the Arity
also. 在
Function
您将找到函数名称作为原子,您也可以获得Module
和Arity
。 You can't write this as function because it would just return this function as current. 你不能把它写成函数,因为它只会将此函数作为当前函数返回。 A macro that gives you the current function name as atom could look like:
一个宏,它为您提供当前函数名称作为原子可能如下所示:
-define(current_function_name(),
element(2, element(2, process_info(self(), current_function)))).
foo() ->
foo = ?current_function_name().
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.