lua中如何实现打印行号和当前函数名?

这篇博客介绍了在 Lua 中如何利用 debug.getinfo 方法获取当前堆栈信息,从而实现打印行号和函数名的功能。示例代码展示了如何创建一个日志模块,通过 ELOG, WLOG, NLOG 和 DLOG 函数进行不同级别的日志输出,便于调试和记录程序运行状态。

lua中如何实现打印行号和当前函数名?

lua中可以使用debug的get_info方法来获取当前的堆栈信息,进而可以打印出相关的环境信息,具体信息包括:

table: 0x7f92b8f19e80
{
    isvararg = false    ,
    what = Lua  ,
    func = function: 0x7f92b7b8d600     ,
    namewhat =  ,
    istailcall = true   ,
    lastlinedefined = 16        ,
    source = @service/db/db_interactionemotion.lua      ,
    linedefined = 7     ,
    currentline = 11    ,
    ntransfer = 0       ,
    short_src = service/db/db_interactionemotion.lua    ,
    ftransfer = 0       ,
    nups = 3    ,
    nparams = 0 ,
}

lua中需要打印行号多半是日志需求,下面是一个demo:

local logger_api = require 'common.logger_api'
local tag = "test"
local test_id = 0

local M = {}

local function get_debuginfo(info)
    --utils.var_dump(info)
    local d = ""
    if info ~= nil and info.short_src ~= nil and info.currentline ~= nil then
      d =  info.short_src .. ":" .. info.currentline .. ":"
    end
    return d
end

function M.ELOG(...)
    local info = debug.getinfo(2)
    local d = get_debuginfo(info)
    logger_api.ERROR(string.format("%s[E]no_%s_%s",d,test_id,tag),...)
end

function M.WLOG(...)
    local info = debug.getinfo(2)
    local d = get_debuginfo(info)
    logger_api.WARN(string.format("%s[W]no_%s_%s",d,test_id,tag),...)
end

function M.NLOG(...)
    logger_api.INFO(string.format("[N]no_%s_%s", test_id,tag), ...)
end

function M.DLOG(...)
    local info = debug.getinfo(2)
    local d = get_debuginfo(info)
    logger_api.DEBUG(string.format("%s[D]no_%s_%s",d,test_id,tag),...)
end
return M

原文出处:https://www.cfanzp.com/lua-debug/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

打杂程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值