在Lua中,如何打印当前函数的名称,如C99 __func__标识符?

x-x*_*x-x 12 lua

像这样的东西:

function foo()
    print( __func__ )
   ...
end
Run Code Online (Sandbox Code Playgroud)

怎么做到呢?

Eph*_*aim 27

#!/usr/bin/lua

local function myFunc()
 print(debug.getinfo(1, "n").name);
end
myFunc()
Run Code Online (Sandbox Code Playgroud)

  • 目前在 Lua 5.3 中返回“nil”。 (2认同)

Chr*_*cke 12

你不能.在lua中,函数是第一类变量.所以他们没有名字.你不妨问"2的名字是什么".仅仅因为某个变量被赋值,值'2'就不会使该变量成为名称2.同样,"someFunc"是一个变量 - 可能是其中之一 - 保存一个特定的函数.

  • 没有。这两个答案在技术上都是正确的。如果-按名称-您想要lua函数的唯一不变的分配名称-__FUNC__为C程序提供的内容-您将无法获得它。如果按名称,您只是想要一个具有该函数作为其值的变量的名称,请使用调试方法来获取该变量,请记住可以重新分配变量,并且多个变量可以包含相同的值-因此“名称”返回此值方式既不独特也不不变。 (3认同)

And*_*uan 6

function __FILE__() return debug.getinfo(2, 'S').source end
function __LINE__() return debug.getinfo(2, 'l').currentline end
function __FUNC__() return debug.getinfo(2, 'n').name end

function printlinefilefunc()
    print("Line at "..__LINE__()..", FILE at "..__FILE__()..", in func: "..__FUNC__())
end
Run Code Online (Sandbox Code Playgroud)

输出:

第 8 行,@./andydebug.lua 中的 FILE,func 中:printlinefilefunc