In Lua, how can you print the name of the current function, like the C99 __func__ identifier?

前端 未结 7 1748
别那么骄傲
别那么骄傲 2021-02-13 03:49

Something like this:

function foo()
    print( __func__ )
   ...
end

How can it be done?

相关标签:
7条回答
  • 2021-02-13 04:10

    Functions don't necessarily have them. It's perfectly legal in Lua to create anonymous functions with no name- and call it, without assigning it one.

    (function()
        print("in anonymous function!")
    end)()
    

    Is perfectly valid Lua. What name do you want to give that function?

    0 讨论(0)
  • 2021-02-13 04:13
    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
    

    Output:

    Line at 8, FILE at @./andydebug.lua, in func: printlinefilefunc

    0 讨论(0)
  • 2021-02-13 04:16
    #!/usr/bin/lua
    
    local function myFunc()
     print(debug.getinfo(1, "n").name);
    end
    myFunc()
    
    0 讨论(0)
  • 2021-02-13 04:28

    You can't. In lua, functions are first class variables. So they don't have names. You might as well ask "what the name of 2" is. Just because some variable was assigned the value '2' doesn't make that variable the name of 2. Likewise "someFunc" is a variable - potentially one of many - that holds a particular function.

    0 讨论(0)
  • 2021-02-13 04:29

    You can try:

    local dbFunc = debug.getinfo(1) and debug.getinfo(1).name or ""
    
    Info
    Info["currentline"] = 1376
    Info["source"] = "@.\mymod.lua"
    Info["short_src"] = ".\mymod.lua"
    Info["nups"] = 13
    Info["isvararg"] = false
    Info["what"] = "Lua"
    Info["lastlinedefined"] = 1570
    Info["func"] = function: 000000000030B440
    Info["istailcall"] = false
    Info["linedefined"] = 1375
    Info["namewhat"] = "field"
    Info["name"] = "ExportDB" <<--- See here the function name
    Info["nparams"] = 4
    

    debug.getinfo(1) Returns this structure of the current execution state of the active function in the stack.

    If n is larger than the number of active functions in the stack, debug.getinfo() returns nil.

    That's why you have to check if it exists before taking *.name and return an empty string if the information is not available

    A it is called inside the ExportDB() function, it return its name

    0 讨论(0)
  • 2021-02-13 04:31

    Use the Debug Library. It provides a getinfo(func) function that returns a table with information about the function.

    0 讨论(0)
提交回复
热议问题