悉野小楼

导航

lua打印调用的函数文件及行数

lua根据调用堆栈可以打印调谁调用了我

 

string.split = function(s, delim)
    local split = {}
    local pattern = "[^" .. delim .. "]+"
    string.gsub(s, pattern, function(v) table.insert(split, v) end)
    return split
end

function getWhoCallsMe()
    local tracebackarr = string.split(debug.traceback(), "\n")
    if #tracebackarr >= 4 then
        -- 正常最少都有4行的
        local tracebackmsg = string.split(tracebackarr[4], " ")[1] --     ./\tE:\\luaXXX/luatest.lua:26: in main chunk
        local msgarr = string.split(tracebackmsg, "/")
        local luaFileInfo = msgarr[#msgarr] -- luatest.lua:26:      
        return luaFileInfo
    end
    return tracebackarr[#tracebackarr]
end

function test()
    local info = getWhoCallsMe()
    print(info)
end

test()
-- 输出 luatest.lua:26:

 

posted on 2024-05-24 15:10  悉野  阅读(14)  评论(0编辑  收藏  举报